一、mybatis demo
1、建表
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
插入两条数据
2、pom文件添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
3、添加配置
<?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>
<!-- 配置数据库连接信息 -->
<environments default="Local">
<environment id="Local">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myDataBase"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
</environment>
</environments>
<!-- 注册mapper.xml文件 -->
<mappers>
<mapper resource="com/sunshine/shine/mapper/UserMapper.xml"/>
</mappers>
</configuration>
4、UserMapper.xml、User
User
package com.sunshine.shine.dao.model;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private Integer sex;
}
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.sunshine.shine.mapper.UserMapper">
<select id="selectOneUser" parameterType="int" resultType="com.sunshine.shine.dao.model.User">
select * from users where id = #{id}
</select>
</mapper>
5、测试
package com.sunshine.shine.Test;
import com.sunshine.shine.dao.model.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
public class MybatisTest {
@Test
public void testMybatis(){
String resource="mybatis-config.xml";
InputStream resourceAsStream = MybatisTest.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession session = sqlSessionFactory.openSession();
String statement ="com.sunshine.shine.mapper.UserMapper.selectOneUser";
User o = session.selectOne(statement,2);
System.out.println(o.getId()+" name="+o.getName()+" sex="+o.getSex());
}
}
输出:
15:14:43.930 [main] DEBUG com.sunshine.shine.mapper.UserMapper.selectOneUser - ==> Preparing: select * from users where id = ?
15:14:43.971 [main] DEBUG com.sunshine.shine.mapper.UserMapper.selectOneUser - ==> Parameters: 2(Integer)
15:14:44.008 [main] DEBUG com.sunshine.shine.mapper.UserMapper.selectOneUser - <== Total: 1
2 name=sunshineGirl sex=0
二、实际应用
1、application.properties 中配置(或对应的环境中自定义配置文件中配置)
#配置数据库连接信息
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/myDataBase?useSSL=false
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
##com.mysql.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = 12345678
#配置扫描mapper.xml文件路径
mybatis.mapper-locations = com/sunshine/shine/mapper/*.xml
2、UserMapper.xml 、UserMapper、UserController
<?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.sunshine.shine.dao.UserMapper">
<select id="selectOneUser" parameterType="java.lang.Integer" resultType="com.sunshine.shine.dao.model.User">
select * from users where id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunshine.shine.dao;
import com.sunshine.shine.dao.model.User;
public interface UserMapper {
User selectOneUser(Integer id);
}
package com.sunshine.shine.controller;
import com.sunshine.shine.Util.JsonData;
import com.sunshine.shine.config.ConfigBean;
import com.sunshine.shine.dao.model.User;
import com.sunshine.shine.dao.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class UserController {
private static final Logger LOGGER =LoggerFactory.getLogger(UserController.class);
@Autowired
private UserMapper userMapper;
@GetMapping("/testMybatis")
public User testMybatis(Integer id){
if(id==null){
id=1;
}
User user = userMapper.selectOneUser(id);
return user;
}
}
3、在main方法的类上加上扫描mapper.xml映射接口的注解
@MapperScan("com.sunshine.shine.dao")
4、运行程序请求 /testMybatis
返回数据:
三、使用MyBatis Generator自动生成
1、pom文件添加mbg插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.9-rc</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
</dependencies>
<configuration>
<!-- 配置文件位置 -->
<configurationFile>${basedir}/src/main/resources/mbgConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
2、添加配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="local" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接地址账号密码-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/myDataBase?useSSL=false"
userId="root"
password="12345678">
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--targetProject与targetPackage配置生成文件的保存路径 -->
<!--生成实体类 -->
<javaModelGenerator targetPackage="com.sunshine.shine.dao.model"
targetProject="src/main/java">
</javaModelGenerator>
<!--生成SQLMAP文件-->
<sqlMapGenerator targetPackage="com.sunshine.shine.mapper"
targetProject="src/main/java">
</sqlMapGenerator>
<!--生成Dao文件-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sunshine.shine.dao"
targetProject="src/main/java">
</javaClientGenerator>
<!--生成对应表及类名-->
<table tableName="books" domainObjectName="books" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
3、直接点击右侧Maven Project->项目->Plugins->mybatis-generator->mybatis-generator:generate
生成文件如下: