使用ssm框架有一段时间了,最近开始想看ssm框架里面的具体东西,于是买了一本书《互联网轻量级整合开发SSM框架》,想把自己从书中获得到的东西给做点记录。
一、 简单介绍
这里从mybatis开始,一般的共识是有四个核心组件:
1. SqlSessionFactoryBuilder : (构造器),采用Builder模式,根据配置或者代码生成SqlSessionFactory。
2. SqlSessionFactory: (工厂接口),使用工厂模式生成SqlSession。
3. SqlSession: (会话):这个是核心接口,主要功能包括三个:
获取Mapper接口
发送SQL给数据库
控制数据库事务
4. SQL Mapper (映射器) : 有Java接口和XML文件(或注解)组成,需要给出对应的SQL和映射规则,它负责发送SQL去执行,并返回结果。
二、栗子
下面是一个小例子,只有mybatis
1、需要的jar包如下:
2. 建立一个简单的maven项目,需要的类如图:
3. 建立日志文件 log4j.properties,日志配置如下:
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
4. 建立mybatis 配置文件mybatis-config.xml 如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases> <!-- 别名 -->
<typeAlias alias="role" type="com.learn.ssn.chapter3.pojo.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/mobile_bi" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="com/learn/ssn/chapter3/mapper/RoleMapper.xml" />
</mappers>
</configuration>
5. 根据mybatis-config.xml 通过SqlSessionFactoryBuilder 构建SqlSessionFactory,采用单例模式,如下:
package com.learn.ssn.chapter3.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
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 resource = "mybatis-config.xml";
InputStream inputStream;
try{
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(IOException e){
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
public static SqlSession openSqlSession(){
if(sqlSessionFactory == null){
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
6. 定一个POJO, Role ,如下:
package com.learn.ssn.chapter3.pojo;
public class Role {
private Long id;
private String roleName;
private String note;
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
public String getRoleName(){
return roleName;
}
public void setRoleName(String roleName){
this.roleName = roleName;
}
public String getNote(){
return note;
}
public void setNote(String note){
this.note = note;
}
}
6. 采用XML方式构建映射器,包括一个借口和一个XML,接口如下:
package com.learn.ssn.chapter3.mapper;
import java.util.List;
import com.learn.ssn.chapter3.pojo.Role;
public interface RoleMapper {
public int insertRole(Role role);
public int deleteRole(Long id);
public int updateRole(Role role);
public Role getRole(Long id);
public List<Role> findRoles(String roleName);
}
7. 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="com.learn.ssn.chapter3.mapper.RoleMapper">
<insert id="insertRole" parameterType="role">
insert into t_role (role_name, 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 role_name = #{roleName}, note = #{note} where id = #{id}
</update>
<select id="getRole" parameterType="role" resultType="role">
select id, role_name as roleName, note from t_role where id = #{id}
</select>
<select id="findRoles" parameterType="string" resultType="role">
select id, role_name as roleName, note from t_role
where role_name like concat('%', #{roleName}, '%' )
</select>
</mapper>
8. 最后一个Main函数,
package com.learn.ssn.chapter3.main;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import com.learn.ssn.chapter3.mapper.RoleMapper;
import com.learn.ssn.chapter3.pojo.Role;
import com.learn.ssn.chapter3.utils.SqlSessionFactoryUtils;
public class Chapter3Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger(Chapter3Main.class);
SqlSession sqlSession = null;
try{
sqlSession = SqlSessionFactoryUtils.openSqlSession();
RoleMapper rolemapper = sqlSession.getMapper(RoleMapper.class);
Role role = rolemapper.getRole(1L);
logger.info(role.getRoleName());
}finally{
if(sqlSession != null){
sqlSession.close();
}
}
}
}
9. 测试结果如下:
DEBUG 2018-05-15 17:11:37,951 org.apache.ibatis.logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG 2018-05-15 17:11:38,021 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-05-15 17:11:38,022 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-05-15 17:11:38,022 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-05-15 17:11:38,022 org.apache.ibatis.datasource.pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
DEBUG 2018-05-15 17:11:38,093 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
DEBUG 2018-05-15 17:11:38,268 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 967765295.
DEBUG 2018-05-15 17:11:38,268 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@39aeed2f]
DEBUG 2018-05-15 17:11:38,270 com.learn.ssn.chapter3.mapper.RoleMapper.getRole: ==> Preparing: select id, role_name as roleName, note from t_role where id = ?
DEBUG 2018-05-15 17:11:38,288 com.learn.ssn.chapter3.mapper.RoleMapper.getRole: ==> Parameters: 1(Long)
DEBUG 2018-05-15 17:11:38,300 com.learn.ssn.chapter3.mapper.RoleMapper.getRole: <== Total: 1
INFO 2018-05-15 17:11:38,301 com.learn.ssn.chapter3.main.Chapter3Main: name1
DEBUG 2018-05-15 17:11:38,301 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.Connection@39aeed2f]
DEBUG 2018-05-15 17:11:38,301 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Closing JDBC Connection [com.mysql.jdbc.Connection@39aeed2f]
DEBUG 2018-05-15 17:11:38,301 org.apache.ibatis.datasource.pooled.PooledDataSource: Returned connection 967765295 to pool.
这是只是初识mybatis的一小小栗子。