java学习路线之 SpringBoot——mybatis搭建

此文章仅作为个人学习内容总结,不保证完全正确,如有错误,欢迎斧正。


说明

ide: intelij

语言: java

快捷键: cmd+N, option+return

重点: springboot+mybatis


一、创建新的项目

1. 创建新的项目,选择 spring Initializr 点击next
2. 输入Group 和 Artifat 点击next
3. 选择Web->Web, sql->(mysql, mybatis) 点击next
4. 输入 Project Name 点击Finish

二、application.properties配置

1. 修改文件名为application.yml (非必要)
2. 加入数据库配置信息,共class中调用

jdbc:
  driver: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/ydl-test?useUnicode=true&characterEncoding=utf8&useSSL=false
  username: root
  password: 123456
# mybatis配置文件路径(main/java/包名/resource下,与application.yml同级)
mybatis_config_path: mybatis-config.xml
# main/java/包名/resource/mapper下, **.xml表示所有xml文件
mapper_path: /mapper/**.xml
# 实体类包名
entity_package: com.zyf.test.dao.entity

3. 在pom.xml中加入

<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>

三、mybatis配置

1. 在 main/resource 下新建文件 mybatis-config.xml, 内容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 使用列标签替换列别名 默认true -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 开启驼峰命名转换:Table{createTime} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

2.在java下创建config的package
3.在config下创建dao,并新建类DataSourceConfiguration

package com.zyf.test.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;

@Configuration
@MapperScan("com.zyf.test.dao.entity")
public class DataSourceConfiguration {
    @Value("${jdbc.driver}")
    private String jdbcDriver;

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String jdbcUsername;

    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name="dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        // 关闭链接后不自动commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}

4.在config/dao下新建类SessionFactoryConfiguration


package com.zyf.test.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class SessionFactoryConfiguration {
    @Value("${mybatis_config_path}")
    private String mybatisConfigFilePath;

    @Value("${mapper_path}")
    private String mapperPath;

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Value("${entity_package}")
    private String entityPackage;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

四、代码部分

1. 在main/java/包名 下创建dao的package, 并分别创建mapper, entity
2.在entity中创建数据库实体类,假设存在user表,则创建User类

package com.zyf.test.dao.entity;

public class User {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

3.在mapper中创建数据库映射类, UserMapper

package com.zyf.test.dao.mapper;

import com.zyf.test.dao.entity.User;

import java.util.List;

public interface UserMapper {

    List<User> getAll();

    User getOne(int id);

    Integer insert(User user);

    void update(User user);

    void delete(int id);

}

4. 在resource下创建文件夹mapper, 并创建UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyf.test.dao.mapper.UserMapper">
    <select id="getAll" resultType="com.zyf.test.dao.entity.User">
        SELECT
          id, name
        FROM user
        ORDER BY id DESC
    </select>
    <select id="getOne" resultType="com.zyf.test.dao.entity.User">
        SELECT
          id, email, name, password, created_at, status
        FROM user
        WHERE id=#{id,jdbcType=INTEGER}
    </select>
    <insert id="insert"
        useGeneratedKeys="true"
        keyProperty="userMapper"
        keyColumn="id" parameterType="com.zyf.test.dao.entity.User">
        INSERT INTO
        user
        (name)
        VALUES
        (#{name})
    </insert>

    <update id="update" parameterType="com.zyf.test.dao.entity.User">
        update user
        <set>
            <if test="name!=null">
                name=#{name}
            </if>
        </set>
        where id=#{id}
    </update>
    <delete id="delete">
        DELETE FROM
        user
        WHERE id=#{id}
    </delete>
</mapper>

五、单元测试

1. 在dao.mapper.UserMapper中,使用option+return,选择create test,全选
2. 编写测试代码

package zyf.demo.dao.mapper;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import static org.junit.Assert.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void getAll() {
        List<User> list = userMapper.getAll();
        assertEquals(0, list.size());
    }

    @Test
    @Ignore
    public void getOne() {
    }

    @Test
    @Ignore
    public void insert() {
    }

    @Test
    @Ignore
    public void update() {
    }

    @Test
    @Ignore
    public void delete() {
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31343581/article/details/79688336
今日推荐