mybatis的资源:链接:https://pan.baidu.com/s/1GxOKQJJrbbeJvAh8xQzShg
提取码:ib4g
mysql的驱动jar包:链接:https://pan.baidu.com/s/1GDqWknmwynDWOmtc35T1Vw
提取码:wfmp
文件 | 作用 |
---|---|
chapterMain.java | 程序入口,拥有main方法 |
RoleMapper.java | 映射器接口 |
RoleMapper.xml | 映射器XML文件,描述映射关系,SQL等内容 |
Role.java | POJO对象 |
SqlSessionFactoryUtils.java | 一个工具类,用于创建SqlSessionFactory和SqlSession对象 |
log4j.propertoes | 日志配置,让后台日志数据Mybatis运行的过程日志 |
mybatis-config.xml | MyBatis配置文件 |
log4j.properties
# Configure logging for testing: optionally with log file
log4j.rootLogger=DEBUG, stdout
# log4j.rootLogger=WARN, stdout, logfile
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=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
注意改为DEBUG
构造一个POJO对象,最终查询会映射到它上面或者将其存到数据库
package com.learn.ssm.chapter3.pojo;
public class Role {
public Role(){};
private int id;
private String roleName;
private String note;
/** setter and getter **/
public int getId() {
return id;
}
public void setId(int 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;
}
}
采用XML方式构建映射器,它包含一个接口和一个xml。这里要实现增删改查,所以要定义一个接口
package com.learn.ssm.chapter3.mapper;
import java.util.List;
import com.learn.ssm.chapter3.pojo.Role;
public interface RoleMapper {
public int insertRole(Role role);
public int deleteRole(int id);
public int updateRole(Role role);
public Role getRole(int id);
public List<Role> findRoles(String roleName);
}
RoleMapper.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.ssm.chapter3.mapper.RoleMapper">
<insert id="insertRole" parameterType="role">
insert into t_role(role_name, note) values(#{roleName}, #{note})
</insert>
<delete id="deleteRole" parameterType="int">
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="int" 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>
这是一些比较简单的SQL语句,insert,delete,select,update元素表示增,删,改,查,而里面的元素id则标识了对应的SQL。parameterType标出了是什么类型的参数,resultType则代表结果映射成为什么类型。
其中insert,delete,和update返回的是影响的条数。
使用mybatis-config.xml构建SqlsessionFactory
<?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="com.learn.ssm.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/ssm?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>
<!--构建SqlsessionFactory -->
<mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/>
<!-- 注解实现映射器 -->
</mappers>
</configuration>
使用mybatis-config.xml文件。通过SQLSessionFactoryBUilder来构建SqlSessionFactory。由于SqlsessionFactory应该采用单例模式。所以使用单例模式
package com.learn.ssm.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 {
//使用单例模式创建SqlSessionFactory
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;
}
// 利用xml生成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();
// 返回sqlsession
}
}
构造方法加入了private关键字,使得其他代码不能通过new的方式来创建它,而加入synchronized关键字加锁。主要是为了防止在多线程中多次实例化SqlsessionFactory对象,从而保证SqlsessionFactory的唯一性。
而openSqlSession方法的作用则是创建sqlsession
接下来是运行代码:
package com.learn.ssm.chapter3.main;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import com.learn.ssm.chapter3.mapper.RoleMapper;
import com.learn.ssm.chapter3.mapper.RoleMapper2;
import com.learn.ssm.chapter3.pojo.Role;
import com.learn.ssm.chapter3.utils.SqlSessionFactoryUtils;
public class chapter3Main {
public static void main(String[] args) {
testRoleMapper();
}
private static void testRoleMapper() {
Logger log = Logger.getLogger(chapter3Main.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.openSqlSession();
// 静态方法返回sqlsession
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
// sqlsession可以获取Mapper接口,通过Mapper接口发送SQL
Role role = roleMapper.getRole(0);
log.info(role.getRoleName());
log.info(role.getId());
log.info(role.getNote());
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
//注解SQL测试
// private static void testRoleMapper2() {
// Logger log = Logger.getLogger(chapter3Main.class);
// SqlSession sqlSession = null;
// try {
// sqlSession = SqlSessionFactoryUtils.openSqlSession();
// RoleMapper2 roleMapper2 = sqlSession.getMapper(RoleMapper2.class);
// Role role = roleMapper2.getRole(1L);
// log.info(role.getRoleName());
// } finally {
// if (sqlSession != null) {
// sqlSession.close();
// }
// }
// }
}
// sqlsession可以获取Mapper接口,通过Mapper接口发送SQL,
通过Sqlsession的getMapper的方法来获取一个Mapper接口,就可以调用他们的方法
public int insertRole(Role role);
public int deleteRole(int id);
public int updateRole(Role role);
public Role getRole(int id);
public List<Role> findRoles(String roleName);
通过SqlSession获取一个RoleMapper的对象,然后通过getRole的方法获取到Role的对象,最后正确关闭SqlSession对象。