1. Mybatis introduction
Mybatis is a persistence layer framework that supports ordinary SQL queries, stored procedures and advanced mapping. It is a semi-automatic ORM persistence layer framework with high SQL flexibility, supports advanced mapping (one-to-one, one-to-many), dynamic SQL, lazy loading and caching features, but its database independence is low .
JDBC->dbutils->MyBatis->Hibernate
Hibernate is a fully automated framework
2. Mybatis Quick Start
First: add jar package
mysql,mybatis,lombok
Note: lombok: (The lombok plug-in of idea must be installed, which can generate get, set, parameterized and non-parameterized structures of entity classes)
<!-- mysql依赖-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
Second: Create a database and table
Facilitate the configuration of mybatis-config.xml
Third: add Mybatis configuration file 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>
<environments default="development">
<environment id="development">
<!-- JDBC:代表使用的事务管理类型,默认打开事务,操作之后需要手动提交-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- ppp代表连接数据库的表-->
<property name="url" value="jdbc:mysql://localhost:3306/ppp"/>
<!-- username代表数据库的用户名-->
<property name="username" value="root"/>
<!-- password代表数据库的密码-->
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
Fourth: Define the entity class corresponding to the table
//以下注解是Lombok中的注解
@Data (包括get、set、toString)
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
}
Fifth: Define the CURD (add, delete, modify, and check) operation for operating the user table
sql mapping file UserMapper.xml
note:
resultType: The data type returned after the query statement is executed. The int type can be omitted, and other types cannot be omitted.
parameterType: indicates the type of the passed parameter, the attribute can not be added
namespace: namespace, give a unique name to the container that currently stores mybatis, which must match the full path of the interface
select: indicates the query label: the sql statement for the query can be placed in the label
id: the only sign, the name must be the same as the interface name;
<?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 namespace="com.zz.dao.UserDao">
<!-- id名字必须要跟接口名字一样-->
<!-- select 代表添加的sql -->
<select id="selectAll" resultType="com.zz.entity.User">
select * from user
</select>
<!-- insert 代表添加的sql insertUser必须和映射dao接口的方法名一致 -->
<insert id="insertUser">
insert into user(username,password) values (#{param1},#{param2})
</insert>
<!-- update 代表修改的sql -->
<update id="updateUser">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<!-- delete 代表删除的sql -->
<delete id="deleteUser">
delete from user where id=#{id}
</delete>
</mapper>
Sixth: Register the userMapper.xml file in the conf.xml file
note:
- The tag of mappers should be placed in <configuration></configuration>
- resource="mapper path" For example: resource="mapper\UserMapper.xml"
<mappers>
<mapper resource="mapper\UserMapper.xml"/>
</mappers>
Seventh: Write test code:
Note: JDBC transaction management opens transactions by default. After adding, deleting and modifying operations, you need to commit the transaction. For example: session.commit();
Ordinary additions, deletions, corrections
For example: haha.selectById
haha: namespace="haha", the name of the mapper.xml namespace
selectById: id="selectById"
- Inquire
Note: selectOne means only query one
selectList() indicates that the query is a list collection type.
public static void main(String[] args) throws Exception {
// 查询
//加载 mybatis 的配置文件(它也加载关联的映射文件)
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//构建 sqlSession 的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中 sql 的 sqlSession
SqlSession session = sessionFactory.openSession();
// 执行sql haha:命名空间的名字
User user = session.selectOne("haha.selectById", 2);
System.out.println(user);
}
2. Add
insert means adding method
// 添加
@Test
public void insert() throws Exception {
// 1.读取mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.读取sqlSessionFaction
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.获取sqlSession对象
SqlSession session = sessionFactory.openSession();
// 4.执行sql
int insert = session.insert("haha.insertUser", new User("峥峥", "111"));
// 增删改需要提交事务
session.commit();
System.out.println(insert);
}
3. Modify
update means the method of modification
//修改
@Test
public void update() throws Exception {
//添加mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 获取sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 读取sqlSession对象
SqlSession session = sessionFactory.openSession();
int update = session.update("haha.updateUser", new User(3, "李四", "333"));
//执行sql
session.commit();
System.out.println(update);
}
4. Delete
delete means delete method
// 删除
@Test
public void delete() throws Exception{
// 1. 添加mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2 获取·sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3 读取sqlSession对象 执行sql语句
SqlSession session = sessionFactory.openSession();
// 4.执行sql
int delete = session.delete("haha.deleteUser", 2);
// 5 提交事务
session.commit();
System.out.println(delete);
}
Operation in actual development:
Note: In actual development, the interface should be used in conjunction with the mapping file
1. The created interface userDao
public interface UserDao {
/**
* 查询所有的用户信息
* @return返回所有的用户信息
*/
List<User> selectAll();
/**
* 添加用户信息
*/
int insertUser(String username,String password);
/**
* 修改用户信息
*/
int updateUser(User user);
/**
* 删除用户信息
*/
int deleteUser(int id);
}
2. Create the mapped file
<?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 namespace="com.zz.dao.UserDao">
<!-- id名字必须要跟接口名字一样-->
<select id="selectAll" resultType="com.zz.entity.User">
select * from user
</select>
<insert id="insertUser">
insert into user(username,password) values (#{param1},#{param2})
</insert>
<select id="selectByuserAndpwd" resultType="com.zz.entity.User">
select * from user where username=#{username} and password=#{password}
</select>
<update id="updateUser">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<delete id="deleteUser">
delete from user where id=#{id}
</delete>
</mapper>
3. Adding, deleting and modifying operations in actual development
- Execute the defined select statement
/**
* 查询全部
* @throws Exception
*/
@Test
public void select()throws Exception{
// 先读取mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 获取sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 读取sqlSession对象
SqlSession session = sessionFactory.openSession();
// 得到对应接口的实现类
UserDao mapper = session.getMapper(UserDao.class);
List<User> users = mapper.selectAll();
// 提交事务
session.commit();
System.out.println(users);
}
- Execute the defined insert statement
// 添加用户
public static void main(String[] args) throws Exception{
// 1.先获取mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.获取sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3 读取sqlSession对象 执行sql语句
SqlSession session = sessionFactory.openSession();
// 4.执行sql
UserDao userDao = session.getMapper(UserDao.class);//获得对应接口的实现类
int i = userDao.insertUser("峥11", "11111");
session.commit();
System.out.println(i);
}
- Execute the defined update statement
/**
* 修改
* @throws Exception
*/
@Test
public void update() throws Exception{
// 先读取mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 获取sqlsessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 读取sqlSessiom对象
SqlSession session = sessionFactory.openSession();
// 得到对应的实现类
UserDao userDao = session.getMapper(UserDao.class);
int i = userDao.updateUser(new User(4, "哈哈哈", "222"));
// 提交事务
session.commit();
System.out.println(i);
}
- Execute the defined delete statement
/**
* 删除
* @throws Exception
*/
@Test
public void delete() throws Exception{
// 读取mybatis-config.xml
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 获取sqlSessionFaction
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 获取到sqlSession对象
SqlSession session = sessionFactory.openSession();
// 获取到接口对应的实现类
UserDao mapper = session.getMapper(UserDao.class);
int i = mapper.deleteUser(5);
session.commit();
System.out.println(i);
}
Precautions
Mismatch may occur in the mapper.xml mapping to the dao layer
The first:
Adding @param to UserDao means to use the name of the parameter as the parameter name of the mapping file
UserMapper.xml: mapper.xml mapping
The second type:
UserMapper.xml: mapper.xml mapping
UserDao medium dao layers