浅谈mybatis
mybatis类同与dao层实现类代码,他的作用我看来就是简化了dao层代码。以前很长的一串代码,可能只需要三、四句即可解决。每次要写的连接数据库代码,皆可省去,减少代码冗余。
mybatis的配置分为xml配置和注解配置:
第一种:XML配置
一、建实体类
@Data //该注解可以帮助省去写变量的set/get以及toSting方法
public class User {
/**
* id
*/
private Long id;
/**
* 姓名
*/
private String name;
/**
* 密码
*/
private String pwd;
}
二、建实现类接口
public interface UserDao {
/**
* 查询所有用户信息
* @return
*/
List<User> getAll();
/**
* 插入数据
* @param user
* @return
*/
int insert(User user);
/**
* 更新信息
* @param user
* @return
*/
int update(User user);
/**
* 根据id,删除信息
* @param id
* @return
*/
int delete(Long id);
}
三、建实现类的xml文件(此文件替代dao层接口的实现类)
<?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.mybatis.dao.UserDao">
<sql id="sqlBase">
select * from user
</sql>
<select id="getAll" parameterType="User" resultType="User">
<include refid="sqlBase"/>
</select>
<insert id="insert" >
insert into user (id,name,pwd) value (#{id},#{name},#{pwd})
</insert>
<update id="update">
update user set
name =#{name},pwd=#{pwd}
where id=#{id}
</update>
<delete id="delete">
delete from user where id=#{id}
</delete>
</mapper>
四、mybatis.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>
<!--有很多配置及语法具体参考官网([https://mybatis.org/mybatis-3/zh/index.html])。-->
<!-- 起别名-->
<typeAliases>
<package name="com.mybatis.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--"user"数据库名-->
<property name="url" value="jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false"/>
<property name="username" value="root"/><!--换成你的数据库用户名-->
<property name="password" value="123456"/><!--数据库密码-->
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描包-->
<package name="com.mybatis.dao"/>
</mappers>
</configuration>
五、测试类
public class Test {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void before() {
try (InputStream config = Resources.getResourceAsStream("mybatis.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
} catch (IOException e) {
e.printStackTrace();
}
}
@org.junit.Test
public void selectAll() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.getAll());
}
@org.junit.Test
public void insert() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setId(3L);
user.setName("张某某");
user.setPwd("123456");
System.out.println(userDao.insert(user));
}
@org.junit.Test
public void update() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setId(3L);
user.setName("张朝天");
user.setPwd("123321");
System.out.println(userDao.update(user));
}
@org.junit.Test
public void delete(){
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.delete(3L));
}
}
番外:每次都写一系列SqlSession语句很麻烦,可以将SqlSession配置到xml文件吗?
方法一:
配置Bean文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置连接池-->
<bean id="db" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 绑定连接池-->
<property name="dataSource" ref="db"/>
<!-- 赋予每个xml链接-->
<property name="mapperLocations" value="classpath:com/mybatis/dao/*.xml"/>
<!-- 与之前一样配置别名,不配置的话,UserDao.xml就要写全称-->
<property name="typeAliases" value="com.mybatis.entity.User"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--方案一-->
<bean id="userMapper" class="com.mybatis.dao.Impl.UserDaoImpl1">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
UserDao实现类UserDaoImpl1:
public class UserDaoImpl1 implements UserDao {
private SqlSessionTemplate sqlSession;
public void setSqlSessionTemplate (SqlSessionTemplate sqlSessionTemplate) {
this.sqlSession = sqlSessionTemplate;
}
@Override
public List<User> getAll() {
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.getAll();
}
@Override
public int insert(User user) {
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.insert(user);
}
@Override
public int update(User user) {
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.update(user);
}
@Override
public int delete(Long id) {
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.delete(id);
}
}
测试类:
public class SqlSessionTest {
@Test
public void getAll(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringDao.xml");
UserDao userDao = (UserDao) context.getBean("userMapper");
System.out.println(userDao.getAll());
}
}
方法二:
将bean文件方案一改为:
<!--方案二-->
<bean id="userMapper2" class="com.mybatis.dao.Impl.UserDaoImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
新建实现类UserDaoImpl2
public class UserDaoImpl2 extends SqlSessionDaoSupport implements UserDao {
@Override
public List<User> getAll() {
SqlSession sqlSession = getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.getAll();
}
@Override
public int insert(User user) {
SqlSession sqlSession = getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.insert(user);
}
@Override
public int update(User user) {
SqlSession sqlSession = getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.update(user);
}
@Override
public int delete(Long id) {
SqlSession sqlSession = getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
return userDao.delete(id);
}
}
测试方法类似
public class SqlSessionTest {
/**
* 方法一的实现类
*/
@Test
public void getAll(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringDao.xml");
UserDao userDao = (UserDao) context.getBean("userMapper");
System.out.println(userDao.getAll());
}
/**
* 方法二的实现类
*/
@Test
public void getInfo(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringDao.xml");
UserDao userDao = (UserDao) context.getBean("userMapper2");
System.out.println(userDao.getAll());
}
}
第二种:注解配置
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>
<package name="com.mybatis.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描包-->
<package name="com.mybatis.dao"/>
</mappers>
</configuration>
新建UserMapper
public interface UserMapper {
/**
* 查询所有用户信息
* @return
*/
@Select("select * from user")
List<User> getAll();
}
测试类(不需要写实现类的xml):
public class AnnotationTest {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void before() {
try (InputStream config = Resources.getResourceAsStream("mybatis.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
} catch (IOException e) {
e.printStackTrace();
}
}
@org.junit.Test
public void selectAll() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.getAll());
}
}