3.1持久层和mybatis
关键词:
不屏蔽SQL
映射机制灵活
提供使用Mapper的接口编程
环境:
3.2Mybatis核心组件
SqlSessionFactoryBuilder(构造器):根据配置或者代码生成SqlSessionFactory,采用分步构建的builder模式
SqlSessionFactory(工厂接口):使用工厂模式生成SqlSession
SqlSession(会话):即可以发送SQL执行返回结果,也可以获取Mapper的接口。
SqlMapper:由一个java接口和XML文件构成,需要对应sql规则
3.2SQLSessionFactory(工厂接口)
使用XML构建SQLSessionFactory
config
<?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 alias="role" type="bean.Role"/>
</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/ssm_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="wang"/>
</dataSource>
</environment>
</environments>
<!--映射文件-->
<mappers>
<mapper resource="bean/Mapper/RoleMapper.xml"/>
</mappers>
</configuration>
使用代码创建SqlSessionFactory的方法
package util;
import bean.Role;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
public class DBUtil {
private PooledDataSource dataSource = null;
private TransactionFactory transactionFactory = null;
private Environment environment = null;
private Configuration configuration = null;
private SqlSessionFactory sqlSessionFactory = null;
public SqlSessionFactory createCon(){
//数据库连接池信息
dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/ssm_mybatis");
dataSource.setUsername("root");
dataSource.setPassword("wang");
//mybatis的JDBC事务方式
transactionFactory = new JdbcTransactionFactory();
environment = new Environment("development",transactionFactory,dataSource);
//创建Configuration对象
configuration = new Configuration(environment);
//注册别名
configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
//加入映射器
configuration.addMapper(RoleMapper.class);
//使用SqlSessionFactoryBuilder构建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory;
}
}
SqlSession
获取Mapper接口;
发送sql;
控制数据库事务;
DefaultSqlSession:单线程
SqlSessionManage:多线程
创建SqlSession
private SqlSession sqlSession= null;
//事务控制伪代码
public void actionController(){
try {
//打开session会话
sqlSession = createCon().openSession();
//做一些处理
//提交
sqlSession.commit();
}catch (Exception e){
sqlSession.rollback();//存在异常回滚
}finally {
//确保资源顺利关闭
if (sqlSession!=null){
sqlSession.close();
}
}
}
映射器
可配置的内容:
描述映射规则
提供sql语句,并配置参数类型,返回类型,缓存刷新等信息
配置缓存
提供动态sql
Role类//引用了lombok1.18.0
package bean;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Role {
private Long id;
private String roleName;
private String note;
}
映射上面的类
接口:
package Mapper;
import bean.Role;
public interface RoleMapper {
public Role getRole();
}
mapper:
<?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="Mapper.RoleMapper">
<select id="getRole" parameterType="long" resultType="role">
select id,role_name as roleName,note from role where id = #{id}
</select>
</mapper>
配置文件中:
<!--映射文件-->
<mappers>
<mapper resource="bean/Mapper/RoleMapper.xml"/>
</mappers>
即为注册该XML文件,用XML方式创建映射器
实例:
目录
pom文件:
<?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>SSM</groupId>
<artifactId>SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
RoleMapper:
实现增删改查
RoleMapper:
<?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="Mapper.RoleMapper">
<insert id="insertRole" parameterType="role">
insert into t_role(roleName,note) values (#{roleName},#{note})
</insert>
<delete id="deleteRole" parameterType="long">
delete from t_role where id = #{id}
</delete>
<update id="updateRole" parameterType="role">
update t_role set roleName = #{roleName}, note = #{note} where id = #{id}
</update>
<select id="getRole" parameterType="long" resultType="role">
select id,roleName,note from t_role where id = #{id}
</select>
<select id="findRoles" parameterType="String" resultType="Role">
select id,roleName,note from t_role where
roleName like concat('%',#{roleName},'%')
</select>
</mapper>
配置文件:
<?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 alias="role" type="bean.Role"/>
</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/ssm_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="wang"/>
</dataSource>
</environment>
</environments>
<!--映射文件-->
<mappers>
<mapper resource="Mapper/RoleMapper.xml"/>
</mappers>
</configuration>
sqlsessionfactory创建:
package util;
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 SqlSessionFactoryUtils {
//防止多线程中多次实例化
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
private SqlSessionFactoryUtils(){}
public static SqlSessionFactory getSqlSessionFactory(){
synchronized (LOCK){
if (sqlSessionFactory != null){
return sqlSessionFactory;
}
String res = "mybatis-config.xml";
InputStream in;
try {
in = Resources.getResourceAsStream(res);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
}catch (IOException e){
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
public static SqlSession openSqlsession(){
if (sqlSessionFactory == null){
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
日志配置文件logr4:
log4j.rootLogger=DEBUG ,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
Client测试:
package test;
import Mapper.RoleMapper;
import bean.Role;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import util.SqlSessionFactoryUtils;
public class Client {
public static void main(String[] args){
Logger logger = Logger.getLogger(Client.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSqlsession();
RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
Role role = mapper.getRole(1L);
logger.info(role.getRoleName());
}finally {
if (sqlSession!=null){
sqlSession.close();
}
}
}
}
result:
数据库连接要确认数据库服务正确开启,用户名密码无误
Backhome1999 发布了6 篇原创文章 · 获赞 0 · 访问量 35 私信 关注本博客大部分内容来自
[Java EE互联网轻量级整合开发SSM框架和Redis实现] --杨开阵,周吉文,梁华辉等.
中国公信出版社,电子工业出版社