MyBatis的初步使用
项目整体结构
1.所需的依赖包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2.编写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>
<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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!--每个mapper.xml都需要在mybatis核心配置中注册-->
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
3.编写mybatis工具类
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
//使用mybatis的第一步,获取sqlSessionFactory对象
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
4.编写数据库对应的实体类
5.编写接口,以及接口的实现(mapper)
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绑定对应的接口(dao/mapper)-->
<mapper namespace="dao.UserDao">
<select id="getUserList" resultType="entity.User">
select * from mybatis.user
</select>
</mapper>
6.测试
在test中创建相对应的测试类
public class UserDaoTest {
@Test
public void test(){
//1 获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。
// 这个关闭操作很重要,为了确保每次都能执行关闭操作,应该把这个关闭操作放到 finally 块中。
try {
//2 调用userDao接口(对应userMapper映射文件),获得结果集
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
}finally {
sqlSession.close();
}
}
}
注意
maven项目不能访问resources之外的配置文件,需要在pom.xml中进行配置
<!--在build中配置resources, 来防止我们资源导出失败问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
CRUD
1、 mapper接口
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(String name);
}
2、 mapper.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="dao.UserMapper">
<select id="getUserList" resultType="entity.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="entity.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="entity.User">
insert into user values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="entity.User">
update user set name = #{name} ,pwd = #{pwd} where id = #{id}
</update>
<delete id="deleteUser" parameterType="String">
delete from user where name = #{name}
</delete>
</mapper>
3、 测试类
public class UserDaoTest {
@Test
public void test(){
//1 获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。
// 这个关闭操作很重要,为了确保每次都能执行关闭操作,应该把这个关闭操作放到 finally 块中。
try {
//2 调用userDao接口(对应userMapper映射文件),获得结果集
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
}finally {
sqlSession.close();
}
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(5);
System.out.println(user);
}finally {
sqlSession.close();
}
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int i = userMapper.addUser(new User(10, "李四", "147"));
if (i>0){
System.out.println("插入成功");
}
sqlSession.commit();
}finally {
sqlSession.close();
}
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int i = userMapper.updateUser(new User(1, "小明", "123"));
if (i>0){
System.out.println("修改成功");
}
sqlSession.commit();
}finally {
sqlSession.close();
}
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int i = userMapper.deleteUser("小明");
if (i>0){
System.out.println("删除成功");
}
sqlSession.commit();
}finally {
sqlSession.close();
}
}
}