一个简单的MyBatis项目
1、log4j.properties,我们把它设为debug级别,以便于调试。生产环境可以设为INFO,本项目放在src下面:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2、Role.java,一个pojo(plain ordinary java object),用于映射:
package com.ssm.pojo;
/**
* Created by czz on 2019/7/23.
*/
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;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", note='" + note + '\'' +
'}';
}
}
3、用XML方式构建映射器,它包含一个接口和一个XML。其中,RoleMapper.java:
package com.ssm.mapper;
import com.ssm.pojo.Role;
import java.util.List;
/**
* Created by czz on 2019/7/23.
*/
public interface RoleMapper {
int insertRole(Role role);
int deleteRole(Long id);
int updateRole(Role role);
Role getRole(Long id);
List<Role> findRoles(String roleName);
}
4、xml构建中的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.ssm.mapper.RoleMapper">
<insert id="insertRole" parameterType="role">
INSERT INTO t_role(role_name,note) VALUES (#{role_name},#{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="long" resultType="role">
SELECT id ,role_name roleName,note FROM t_role WHERE id = #{id}
</select>
<select id="findRoles" parameterType="long" resultType="com.ssm.pojo.Role">
SELECT id ,role_name roleName,note FROM t_role WHERE role_name LIKE concat('%',#{roleName},'%')
</select>
</mapper>
5、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>
<!-- 全局setting配置,根据需要添加 -->
<!-- 配置别名 -->
<typeAliases>
<typeAlias type="com.ssm.pojo.Role" alias="role"/>
</typeAliases>
<!-- 配置数据库环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.ssm.mapper"/>
</mappers>
</configuration>
6、由于SqlSessionFactory应该采用单例模式,所以这里采用单例模式,利用SqlSessionFactoryBuilder来构建它:
package com.ssm.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by czz on 2019/7/24.
*/
public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory = null;
//防止其他代码通过new的方式创建它
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;
}
}
}
7、运行代码:
package com.ssm.chapter3.main;
import com.ssm.mapper.RoleMapper;
import com.ssm.pojo.Role;
import com.ssm.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
/**
* Created by czz on 2019/7/24.
*/
public class Chapter3Main {
public static void main(String[] args) {
Logger log = Logger.getLogger(Chapter3Main.class);
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = roleMapper.getRole(1L);
log.info(role.getRoleName());
}finally {
if (sqlSession!=null){
sqlSession.close();
}
}
}
}
8、jar包下载:
(1)mybatis 3.5.2(当前最新版)
官网
百度云 :提取码:xnjz
(2)数据库驱动包(mysql):
百度云 :提取码:c963
大家有兴趣也可以关注我的公众号查看文章。
------愿来生只做陌上的看花人,无须入尘缘,仅行于陌上,看一川风花,无爱无伤-----