MyBatis 实例
-
MyBatis简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
-
项目实例
-
个人理解,仅供参考
1.创建一个普通的maven项目
2.在pom.xml中导入依赖
<!-- 导入依赖 -->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit 这个使用来测试的 @Test 注解-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
注意在pom.xml配置如下,防止资源导入不成功问题
<!-- 在maven中,约定大于配置,在pom中添加此文件可以解决 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
在resources目录下编写MyBatis核心配置文件mybatis-config.xml,自定义填写数据库信息
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--这是数据库的配置文件,负责存储连接数据库的信息-->
<configuration>
<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/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--这里注册Mapper信息-->
<mappers>
<mapper resource="com/mao/dao/UserDaoMapper.xml" />
</mappers>
</configuration>
3.测试数据库建立表结构
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`password`) values (1,'王二','123456'),(2,'张三','abcdef'),(3,'李四','987654');
4.创建如下的包结构
5.编写工具类utils下MybatisUtils
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory; //提升作用域
//获取工厂,固定代码
static {
try {
// 获取MyBatis核心配置文件mybatis-config.xml,连接数据库,(创建)映射到sqlSessionFactory.openSession()的SqlSession对象
String resource="mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取sqlSession
//SqlSession完全包含了面向对象数据库执行SQL命令所需的方法
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession();}
}
6.在pojo包下创建User实体类
package com.mao.pojo;
// 实体类User,对应User表
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
7.在dao包下创建编写Mapper接口类UserDao.java,并创建Mapper.xml(可以理解为像UserDao接口的实现类的配置)
public interface UserDao {
List<User> getUserList();
}
<?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">
<!--namespace:命名空间,绑定mapper/Dao接口-->
<mapper namespace="com.mao.dao.UserDao">
<!--id:接口的方法,resultType:接口的返回值类型,test为数据库名称-->
<select id="getUserList" resultType="com.mao.pojo.User">
select * from test.user
</select>
</mapper>
然后记得在MyBatis核心配置文件mybatis-config.xml中注册Mapper
<!--这里注册Mapper信息-->
<mappers>
<mapper resource="com/mao/dao/UserDaoMapper.xml" />
</mappers>
8.测试
public class UserDaoTest {
@Test
public void test(){
//获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
try{
//获取mapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> list = mapper.getUserList();
for (User u:list){
System.out.println(u);
}
//不推荐使用
// List<User> list = sqlSession.selectList("com.qian.dao.UserDao.getUserList");
// for (User user : list) {
// System.out.println(user);
// }
}finally {
//关闭SqlSession
sqlSession.close();
}
}
}
其他操作(增删改查)
- 在接口定义
public interface UserDao {
List<User> getUserList();
// 增删改查
// 根据id查询
User getUserById(int id);
// 增加
int addUser(User user);
int updateUser(User user);
int deleteUserById(int id);
}
- 在实现mapper中添加相应的配置和实现的具体sql语句
<mapper namespace="com.mao.dao.UserDao">
<!--id:接口的方法,resultType:接口的返回值类型-->
<select id="getUserList" resultType="com.mao.pojo.User">
select * from test.user
</select>
<select id="getUserById" resultType="com.mao.pojo.User" parameterType="int">
select * from test.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.mao.pojo.User" >
insert into test.user (id,name,password) values (#{id},#{name},#{password})
</insert>
<update id="updateUser" parameterType="com.mao.pojo.User">
update test.user set name=#{name}, password=#{password} where id = #{id}
</update>
<delete id="deleteUserById" parameterType="int">
delete from test.user where id = #{id}
</delete>
</mapper>
- 测试
public class UserDaoTest {
@Test
public void test(){
//获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//获取mapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> list = mapper.getUserList();
for (User u:list){
System.out.println(u);
}
sqlSession.close();
}
@Test
public void testGetUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User u = mapper.getUserById(1);
System.out.println(u.toString());
sqlSession.close();
}
@Test
public void testAddUser(){
// 获取sqlsession
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 绑定mapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
int i = mapper.addUser(new User(5, "Jim", "12321312"));
System.out.println(i);
// 增删改,提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int i = mapper.updateUser(new User(1, "admin", "111111"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void testDeleteUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int i = mapper.deleteUserById(1);
sqlSession.commit();
sqlSession.close();
}
}
注意!!
- 增删改一定要提交事务: sqlSession.commit();