SpringBoot整合Mybatis

Mybatis核心配置

<?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>
    <!--default表示默认使用的环境-->
    <environments default="development">
        <!--
			其中的一个环境 连接的数据库是powernode
			一般一个数据库会对应一个SqlSessionFactory对象
			一个环境environment会对应一个SqlSessionFactory对象
  		-->
    	<environment id="development">
            <!--
				MyBatis事务管理器接口Transaction有两个实现类
				如果type="JDBC"那么底层会实例化JdbcTransaction对象
				如果type="MANAGED"那么底层会实例化ManagedTransaction对象
			-->
            <transactionManager type="JDBC" />
            <!--
				datasource配置:
					1、dataSource被称为数据源
					2、dataSource为程序提供Connection对象
					3、数据源实际上是一套规范,JDK中有这套规范:javax.sql.DataSource
					4、type有三种值可选其一:
						POOLED:使用MyBatis自己实现的数据库连接池
						UNPOOLED:不适用MyBatis的数据库连接池,每一次请求过来创建新的Connection对象
						JNDI:集成其它第三方的数据库连接池,这是一套规范,大部分Web容器都实现了此规范
			-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/powernode"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
        	</dataSource>
    	</environment>
        
        <!--MyBatis另外一个环境,也就是连接的数据库是另一个数据库MyBatis-->
        <environment id="mybatisDB">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
        	</dataSource>
   		</environment>     
</environments> 
    <!--通过此标签找到映射文件,实际在SpringBoot中的yml配置文件中变成:mybatis:mapper-locations-->
    <mappers>
        <package name="com.chf.mapper" />
    </mappers>
</configuration>
@SpringBootTest
public class ConfigurationTest{
	@Test
	void testEnvironment() throws Exception{
		//获取SqlSessionFactory对象(采用默认方式获取)
		SqlSessionFactoryBuilder ssf = new SqlSessionFactoryBuilder();
        //采用这种方式获取的就是默认的环境
        SqlSessionFactory sqlSessionFactory = ssf.build(Resources.getResourceAsStream("MyBatisConfig.xml"));
        //这种方式通过id获取的是指定的环境
        SqlSessionFactory sqlSessionFactory = ssf.build(Resources.getResourceAsStream("MyBatisConfig.xml"),"mybatisDB");
	}
}

1.新建一个Maven父工程,删除src目录

2.新建一个子工程

3.导入依赖

父工程pom.xml

<properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.7.6</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

子工程pom.xml

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.2</version>
        </dependency>

4.新建一个application.yml或properties(springBoot默认扫描application配置文件

#datasource
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: 123456

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.ykh.pojo
  configuration:
    #开启驼峰命名
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


5.编写主启动类

主启动类下的包都会被扫描到哪些需要bean注册到IOC容器中

@SpringBootApplication
public class MyBatisSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBatisSpringBootApplication.class);
    }
}

6.编写一个接口测试环境是否搭建成功

@RestController
public class HelloController {

    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }

}

启动,访问localhost:8080/hello

搭建成功

7.编写pojo实体类,mapper和对应的mapper.xml文件

@Mapper
public interface UserMapper {

    List<User> selectAll();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;

    private String name;

    private String password;
}
<?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.ykh.mapper.UserMapper">

    <resultMap id="userMap" type="user">
        <result property="password" column="pwd"/>
    </resultMap>

    <select id="selectAll" resultMap="userMap">
        select * from user
    </select>
</mapper>

8.测试

@SpringBootTest
public class MyBatisTest {

    @Autowired
    private UserMapper userMapper;
    
    @Test
    public void test01() throws SQLException {
        List<User> users = userMapper.selectAll();
        System.out.println(users);

    }
}

1.插入一条数据

mapper接口

int insert(User user);

mapper.xml

<insert id="insert" parameterType="user">
        insert into user (name,pwd) values(#{name},#{password})
    </insert>

实体类加上@builder注解

@Builder
public class User {

测试,直接用builder创建对象,简化代码

@Test
public void test02() {
    User user = User.builder().name("张三").password("5201314").build();
    int result = userMapper.insert(user);
    System.out.println(result);

}

2.删除一条数据

mapper

int delete(Integer id);

mapper.xml

<delete id="delete" parameterType="Integer">
        delete from user where id = #{id}
    </delete>

测试

@Test
    public void test03() {
        Integer id = 20;

        int result = userMapper.delete(id);
        System.out.println(result);

    }

3.更新

mapper

int update(User user);

mapper.xml 

如果加<set>标签,就可以自动消除逗号

<update id="update" parameterType="User">
        update user 
        <set>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="password != null ">
            pwd = #{password},
        </if>
        </set>
        where id = #{id}
    </update>

测试

@Test
    public void test04() {
        User user = User.builder().name("哆可酱").id(19).build();
        System.out.println("pwd==="+user.getPassword());
        int result = userMapper.update(user);
        System.out.println(result);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值