文章目录
一、创建数据库与表
二、基于配置文件方式使用MyBatis
2、添加相关依赖 3、创建用户实体类 4、创建用户映射器配置文件 5、创建MyBatis配置文件 6、创建日志属性文件 7、测试用户操作 1)创建用户操作测试类 2)测试按编号查询用户记录 3)测试查询全部用户记录
三、采用接口方式使用MyBatis 1、创建用户映射器接口 2、测试用户映射器接口 1)创建用户映射器接口测试类 2)测试按编号查询用户记录 3)测试查询全部用户记录
四、利用配置类与注解方式使用MyBatis
2、创建新的用户映射器接口测试类 3、修改用户映射器接口 4、运行新的用户映射器接口测试类
一、创建数据库与表
1、创建数据库
在Navicat里创建MySQL数据库 - testdb,采用utf8mb4字符集
2、创建用户表
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
3、添加表记录
INSERT INTO `t_user` VALUES ('1', '李洪刚', '20', '江阳区嘉裕花园3栋四楼15#');
INSERT INTO `t_user` VALUES ('2', '王云华', '30', '纳溪区大渡镇红鱼村三大队');
INSERT INTO `t_user` VALUES ('3', '郑小翠', '21', '江阳区老窖花园2栋五楼15号');
二、基于配置文件方式使用MyBatis
1、创建Maven项目
2、添加相关依赖
< ? xml version= "1.0" encoding= "UTF-8" ? >
< project xmlns= "http://maven.apache.org/POM/4.0.0"
xmlns: xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "http: / / maven. apache. org/ POM/ 4.0 .0
http: / / maven. apache. org/ xsd/ maven- 4.0 .0 . xsd">
< modelVersion> 4.0 .0 < / modelVersion>
< groupId> net. hw. mybatis< / groupId>
< artifactId> MyBatisDemo < / artifactId>
< version> 1.0 - SNAPSHOT< / version>
< build>
< plugins>
< plugin>
< groupId> org. apache. maven. plugins< / groupId>
< artifactId> maven- compiler- plugin< / artifactId>
< configuration>
< source> 8 < / source>
< target> 8 < / target>
< / configuration>
< / plugin>
< / plugins>
< / build>
< dependencies>
< dependency>
< groupId> org. mybatis< / groupId>
< artifactId> mybatis< / artifactId>
< version> 3.5 .13 < / version>
< / dependency>
< dependency>
< groupId> mysql< / groupId>
< artifactId> mysql- connector- java< / artifactId>
< version> 5.1 .49 < / version>
< / dependency>
< dependency>
< groupId> junit< / groupId>
< artifactId> junit< / artifactId>
< version> 4.13 .2 < / version>
< / dependency>
< dependency>
< groupId> log4j< / groupId>
< artifactId> log4j< / artifactId>
< version> 1.2 .17 < / version>
< / dependency>
< / dependencies>
< / project>
3、创建用户实体类
package net. xxr. mybatis. bean ;
public class User {
private int id;
private String name;
private int age;
private String address;
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
this . age = age;
}
public String getAddress ( ) {
return address;
}
public void setAddress ( String address) {
this . address = address;
}
@Override
public String toString ( ) {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}' ;
}
}
4、创建用户映射器配置文件
在resources
目录里创建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= "net.xxr.mybatis.mapper.UserMapper" >
< resultMap id= "userMap" type= "User" >
< result column= "id" jdbcType= "INTEGER" property= "id" javaType= "int" / >
< result column= "name" jdbcType= "VARCHAR" property= "name" javaType= "String" / >
< result column= "age" jdbcType= "INTEGER" property= "age" javaType= "int" / >
< result column= "address" jdbcType= "VARCHAR" property= "address" javaType= "String" / >
< / resultMap>
< ! -- 按编号查询用户记录-- >
< select id= "findById" parameterType= "int" resultType= "User" >
SELECT * FROM t_user WHERE id = #{ id} ;
< / select>
< ! -- 查询全部用户记录-- >
< select id= "findAll" resultMap= "userMap" >
SELECT * FROM t_user;
< / select>
< / mapper>
5、创建MyBatis配置文件
在resources
目录里创建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>
< ! -- 配置实体类别名-- >
< typeAliases>
< typeAlias type= "net.xxr.mybatis.bean.User" alias= "User" / >
< / typeAliases>
< ! -- 配置数据库环境-- >
< environments default = "development" >
< environment id= "development" >
< ! -- 配置事务管理器-- >
< transactionManager type= "JDBC" / >
< ! -- 配置数据源-- >
< dataSource type= "POOLED" > < ! -- 数据库连接池-- >
< property name= "driver" value= "com.mysql.jdbc.Driver" / >
< property name= "url" value= "jdbc:mysql://localhost:3306/testdb?useSSL=false" / >
< property name= "username" value= "root" / >
< property name= "password" value= "root" / >
< / dataSource>
< / environment>
< / environments>
< ! -- 配置实体关系映射器文件-- >
< mappers>
< mapper resource= "mapper/UserMapper.xml" / >
< / mappers>
< / configuration>
6、创建日志属性文件
在resources
目录里创建log4j.properties
文件
log4j. rootLogger= WARN, stdout, logfile
log4j. appender. stdout= org. apache. log4j. ConsoleAppender
log4j. appender. stdout. layout= org. apache. log4j. PatternLayout
log4j. appender. stdout. layout. ConversionPattern= % d % p [ % c] - % m% n
log4j. appender. logfile= org. apache. log4j. FileAppender
log4j. appender. logfile. File= target/ mybatis. log
log4j. appender. logfile. layout= org. apache. log4j. PatternLayout
log4j. appender. logfile. layout. ConversionPattern= % d % p [ % c] - % m% n
7、测试用户操作
1)创建用户操作测试类
在test/java
目录里创建net.xxr.mybatis.bean
包,然后在包里创建测试类 - TestUserOperation
package net. xxr. mybatis. bean ;
import org. apache. ibatis. io. Resources ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ;
import org. junit. After ;
import org. junit. Before ;
import org. junit. Test ;
import java. io. IOException ;
import java. io. Reader ;
import java. util. List ;
public class TestUserOperation {
private SqlSession sqlSession;
@Before
public void init ( ) {
try {
Reader reader = Resources . getResourceAsReader ( "mybatis-config.xml" ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( reader) ;
sqlSession = factory. openSession ( ) ;
System . out. println ( "SQL会话已创建。" ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
@Test
public void testFindById ( ) {
int id = 10 ;
User user = sqlSession. selectOne ( "net.xxr.mybatis.mapper.UserMapper.findById" , id) ;
if ( user != null ) {
System . out. println ( user) ;
} else {
System . out. println ( "编号为[" + id + "]的用户未找到。" ) ;
}
}
@Test
public void testFindAll ( ) {
List < User > users = sqlSession. selectList ( "net.xxr.mybatis.mapper.UserMapper.findAll" ) ;
users. forEach ( user -> System . out. println ( user) ) ;
}
@After
public void destroy ( ) {
sqlSession. close ( ) ;
System . out. println ( "SQL会话已关闭。" ) ;
}
}
2)测试按编号查询用户记录
运行测试方法 - testFindById()
,查看结果
3)测试查询全部用户记录
运行测试方法 - testFindAll()
,查看结果
三、采用接口方式使用MyBatis
1、创建用户映射器接口
创建net.xxr.mybatis.mapper
包,然后在包里创建用户映射器接口 - UserMapper
package net. xxr. mybatis. mapper ;
import net. xxr. mybatis. bean. User ;
import org. apache. ibatis. annotations. Select ;
import java. util. List ;
public interface UserMapper {
User findById ( int id) ;
List < User > findAll ( ) ;
}
2、测试用户映射器接口
1)创建用户映射器接口测试类
在test/java
里创建net.xxr.mybatis.mapper
包,然后在包里创建测试类 - TestUserMapper
package net. xxr. mybatis. mapper ;
import net. xxr. mybatis. bean. User ;
import org. apache. ibatis. io. Resources ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ;
import org. junit. After ;
import org. junit. Before ;
import org. junit. Test ;
import java. io. IOException ;
import java. io. Reader ;
import java. util. List ;
public class TestUserMapper {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init ( ) {
try {
Reader reader = Resources . getResourceAsReader ( "mybatis-config.xml" ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( reader) ;
sqlSession = factory. openSession ( ) ;
userMapper = sqlSession. getMapper ( UserMapper . class ) ;
System . out. println ( "sql会话已创建。" ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
@Test
public void testFindById ( ) {
int id = 1 ;
User user = userMapper. findById ( id) ;
if ( user != null ) {
System . out. println ( user) ;
} else {
System . out. println ( "编号为[" + id + "]的用户未找到。" ) ;
}
}
@Test
public void testFindAll ( ) {
List < User > users = userMapper. findAll ( ) ;
users. forEach ( user -> System . out. println ( user) ) ;
}
@After
public void destroy ( ) {
sqlSession. close ( ) ;
System . out. println ( "sql会话已关闭。" ) ;
}
}
2)测试按编号查询用户记录
运行测试方法 - testFindById()
3)测试查询全部用户记录
运行测试方法 - testFindAll()
四、利用配置类与注解方式使用MyBatis
1、创建MyBatis配置类
在net.xxr.mybatis
包里创建config子包,然后在子包里创建MyBatisConfig类
package net. xxr. mybatis. config ;
import org. apache. ibatis. datasource. pooled. PooledDataSource ;
import org. apache. ibatis. mapping. Environment ;
import org. apache. ibatis. session. Configuration ;
import org. apache. ibatis. transaction. TransactionFactory ;
import org. apache. ibatis. transaction. jdbc. JdbcTransactionFactory ;
import javax. sql. DataSource ;
public class MyBatisConfig {
public static Configuration getConfiguration ( ) {
Configuration configuration = null ;
TransactionFactory transactionFactory = new JdbcTransactionFactory ( ) ;
DataSource dataSource = new PooledDataSource (
"com.mysql.jdbc.Driver" ,
"jdbc:mysql://localhost:3306/testdb?useSSL=false" ,
"root" ,
"root"
) ;
Environment environment = new Environment ( "development" , transactionFactory, dataSource) ;
configuration = new Configuration ( environment) ;
return configuration;
}
}
2、创建新的用户映射器接口测试类
在test/java
的net.xxr.mybatis.mapper
包里创建TestUserMapperNew
类
package net. xxr. mybatis. mapper ;
import net. xxr. mybatis. bean. User ;
import net. xxr. mybatis. config. MyBatisConfig ;
import org. apache. ibatis. io. Resources ;
import org. apache. ibatis. session. Configuration ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ;
import org. junit. After ;
import org. junit. Before ;
import org. junit. Test ;
import java. io. IOException ;
import java. io. Reader ;
import java. util. List ;
public class TestUserMapperNew {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init ( ) {
Configuration configuration = MyBatisConfig . getConfiguration ( ) ;
configuration. addMapper ( UserMapper . class ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( configuration) ;
sqlSession = factory. openSession ( ) ;
userMapper = sqlSession. getMapper ( UserMapper . class ) ;
System . out. println ( "sql会话已创建。" ) ;
}
@Test
public void testFindById ( ) {
int id = 1 ;
User user = userMapper. findById ( id) ;
if ( user != null ) {
System . out. println ( user) ;
} else {
System . out. println ( "编号为[" + id + "]的用户未找到。" ) ;
}
}
@Test
public void testFindAll ( ) {
List < User > users = userMapper. findAll ( ) ;
users. forEach ( user -> System . out. println ( user) ) ;
}
@After
public void destroy ( ) {
sqlSession. close ( ) ;
System . out. println ( "sql会话已关闭。" ) ;
}
}
3、修改用户映射器接口
package net. xxr. mybatis. mapper ;
import net. xxr. mybatis. bean. User ;
import org. apache. ibatis. annotations. Select ;
import java. util. List ;
public interface UserMapper {
@Select ( "SELECT * FROM t_user WHERE id = #{id}" )
User findById ( int id) ;
@Select ( "SELECT * FROM t_user" )
List < User > findAll ( ) ;
}
4、运行新的用户映射器接口测试类
运行测试方法testFindById(),查看结果 运行测试方法testFindAll(),查看结果