1、认识Mybatis
MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录.
1)MyBATIS 目前提供了三种语言实现的版本,包括:Java、.NET以及Ruby。(我主要学习java,就讲java的使用)
2)它提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。
3)mybatis与hibernate的对比?
mybatis提供一种“半自动化”的ORM实现。
这里的“半自动化”,是相对Hibernate等提供了全面的数据库封装机制的“全自动化”ORM实现而言,“全自动”ORM实现了POJO和数据库表之间的映射,以及 SQL 的自动生成和执行。
而mybatis的着力点,则在于POJO与SQL之间的映射关系。
2、基于配置文件的CRUD 使用的mybatis的版本是3.1.1
User.java
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
User.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.sram.pojo.User">
<!-- 插入语句 -->
<insert id="add" parameterType="com.sram.pojo.User">
INSERT INTO t_user(USERNAME,PASSWORD) VALUES(#{username},#{password});
</insert>
<!-- 更新语句 -->
<update id="update" parameterType="com.sram.pojo.User">
UPDATE t_user SET USERNAME=#{username},PASSWORD=#{password} WHERE ID=#{id};
</update>
<!-- 删除语句 -->
<delete id="delete" parameterType="int">
DELETE FROM t_user WHERE ID=#{id};
</delete>
<!-- 查询集合 -->
<select id="list" resultType="com.sram.pojo.User">
SELECT ID,USERNAME,PASSWORD FROM t_user;
</select>
<!-- 查询单个 -->
<select id="load" resultType="com.sram.pojo.User" parameterType="int">
SELECT ID,USERNAME,PASSWORD FROM t_user where ID=#{id};
</select>
</mapper>
Mybatis获取session的工具类MybatisUtil
public class MyBatiesUtil {
private static SqlSessionFactory factory;
//加载一次配置文件
static{
try {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//得到sqlSession
public static SqlSession getSqlSession(){
return factory.openSession();
}
}
数据库的配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = rrb
日志配置文件log4j.properties
#--------------------------------
#
log4j.rootLogger=INFO, stdout
#log4j.logger.test=info
#log4j.logger.org.apache.jasper = DEBUG
#log4j.logger.org.apache.catalina.startup.TldConfig = DEBUG
#log4j.logger.org.apache.catalina.session.ManagerBase = DEBUG
#log4j.logger.com.fiscal = DEBUG
#log4j.logger.com.system = DEBUG
log4j.logger.com.ibatis = DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner = DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = DEBUG
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.fileout=org.apache.log4j.RollingFileAppender
#log4j.appender.fileout.File=e:/log/ibatis.log
#log4j.appender.fileout.MaxFileSize=10000KB
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} :%m%n
#log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
#log4j.appender.fileout.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n
#log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
# log4j.logger.org=info
Mybatis配置文件mybatis-config.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>
<!-- 读取配置文件 -->
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development" >
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 将mapper文件加入到配置文件中 -->
<mappers>
<mapper resource="com/sram/pojo/User.xml"/>
</mappers>
</configuration>
测试CRUD的测试类
public class UserTest {
//测试配置添加方法
@Test
public void add(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = new User("张三","123");
session.insert(User.class.getName()+".add",user);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试配置更新方法
@Test
public void update(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = new User(9,"李四","567");
session.update(User.class.getName()+".update",user);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试配置删除方法
@Test
public void delete(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
session.delete(User.class.getName()+".delete",10);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试配置查询集合方法
@Test
public void list(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
List<User> list = null;
try {
list = session.selectList(User.class.getName()+".list");
System.out.println(list);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试配置查询单个方法
@Test
public void load(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = session.selectOne(User.class.getName()+".load",9);
System.out.println(user.getUsername());
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
}
3、基于注解的CRUD 使用的mybatis的版本是3.1.1
User.java
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
UserMapper.java
public interface UserMapper {
@Insert("INSERT INTO t_user(USERNAME,PASSWORD) VALUES(#{username},#{password})")
public void addUser(User user);
@Update("UPDATE t_user SET USERNAME=#{username},PASSWORD=#{password} WHERE ID=#{id}")
public void update(User user);
@Delete("DELETE FROM t_user WHERE ID=#{id}")
public void delete(int id);
@Select("SELECT ID,USERNAME,PASSWORD FROM t_user")
public List<User> list();
@Select("SELECT ID,USERNAME,PASSWORD FROM t_user where ID=#{id}")
public User load(int id);
}
mybatis获取session的工具类 MybatisUtils.java
public class MyBatisUtil {
private static SqlSessionFactory factory;
//加载一次配置文件
static{
try {
InputStream in = Resources.getResourceAsStream("mybaties-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//得到sqlSession
public static SqlSession getSqlSession(){
return factory.openSession();
}
数据库的配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = rrb
日志配置文件log4j.properties
#--------------------------------
#
log4j.rootLogger=INFO, stdout
#log4j.logger.test=info
#log4j.logger.org.apache.jasper = DEBUG
#log4j.logger.org.apache.catalina.startup.TldConfig = DEBUG
#log4j.logger.org.apache.catalina.session.ManagerBase = DEBUG
#log4j.logger.com.fiscal = DEBUG
#log4j.logger.com.system = DEBUG
log4j.logger.com.ibatis = DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner = DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = DEBUG
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.fileout=org.apache.log4j.RollingFileAppender
#log4j.appender.fileout.File=e:/log/ibatis.log
#log4j.appender.fileout.MaxFileSize=10000KB
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} :%m%n
#log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
#log4j.appender.fileout.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n
#log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
# log4j.logger.org=info
mybatis配置文件mybatis-confg.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>
<!-- 读取配置文件 -->
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development" >
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 将mapper文件加入到配置文件中 -->
<mappers>
<mapper class="com.sram.mapper.UserMapper"/>
</mappers>
</configuration>
测试类
public class UserTest {
//测试注解添加方法
@Test
public void add(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = new User("张三","123");
session.getMapper(UserMapper.class).addUser(user);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试注解更新方法
@Test
public void update(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = new User(13,"李四","567");
session.getMapper(UserMapper.class).update(user);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试注解删除方法
@Test
public void delete(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
session.getMapper(UserMapper.class).delete(14);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试注解查询集合方法
@Test
public void list(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
List<User> list = null;
try {
list = session.getMapper(UserMapper.class).list();
System.out.println(list);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
//测试注解查询单个方法
@Test
public void load(){
//得到sqlSession
SqlSession session = MyBatiesUtil.getSqlSession();
try {
User user = session.getMapper(UserMapper.class).load(13);
System.out.println(user);
//事务提交
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
}
}
}