本人只是刚刚学习MyBatis,作为学习路程的记录,写的不好,不完善的地方请多多包涵;
首先,先比较一下Hibernate和MyBatis两种框架之间的区别:
两种都是ORM框架,但是Hibernate属于全自动化,而MaBatis则属于半自动化,也就是说Hibernate的SQL语句是会自动生产的,而MyBatis的话,需要在xml文件配置一个SQL的模板,这是全自动化和半自动化的含义;那么问题来了,为什么不用更方便的Hibernate呢?
这是因为在一些特殊的情况下,Hibernate反而不好用了:
有些数据来自现有的数据库,出于安全的考虑,只给出几条SQL语句或存储过程,具体表结构不予公开;
开发规范要求,所有牵涉到业务逻辑部分的数据库操作,必须在数据库层由存储过程来实现;
如果系统的数据处理量巨大,性能要求极为苛刻,而Hibernate自动生成的sql语句显然没有经过人工优化,不能高度优化;
总结以上就是:出于安全和性能的考虑,单纯的全自动不能满足行业的开发,因此MyBatis应运而生;
下面是MyBatis实现基本增删改查的基本步骤:
1,导入jar包:
2,编写POJO:
因为MyBatis的优化就是体现在以面对对象的编程机制去操纵数据库,所以,先要有一个POJO来映射相应数据库中的属性;
package org.fkit.domain; public class User { private Integer id;
private String name;
private String sex;
private Integer age;
public User(){
super();
}
public User(String name,String sex,Integer age){
super();
this.name = name;
this.sex = sex;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
} }
3,配置MyBatis连接的数据库的相关参数属性;
这个地方就有个坑了,我调了一天的BUG,我们前面说过,MyBatis的优化就是体现在以面对对象的编程机制去操纵数据库,那么如何将这个POJO映射到MyBatis对应的数据库属性上呢?你需要这样一段代码:
<typeAliases>
<typeAlias alias="user" type="org.fkit.domain.User"/>
</typeAliases>
同时,要按照"(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".
也就是说必须要先写settings标签之后,再写typeAliases标签;这是一个顺序的问题;
<?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>
<settings>
<setting name= "logImpl" value = "LOG4J"/>
</settings>
<typeAliases>
<typeAlias alias="user" type="org.fkit.domain.User"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type = "JDBC"/>
<dataSource type = "POOLED">
<property name = "driver" value="com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name = "username" value = "root"/>
<property name = "password" value = "986532"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource = "org/fkit/mapper/UserMapper.xml"/>
</mappers>
</configuration>
4,建立SQL语句模板;
前面提到,MyBatis的半自动化机制,就是要编写相应的SQL语句模板,所以我们需要这样一个文件;我想叫它做映射文件;
<?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 = "org.fkit.mapper.UserMapper">
<insert id = "save" parameterType ="user" useGeneratedKeys = "true">
INSERT INTO TB_USER(name,sex,age) VALUES(#{name},#{sex},#{age})
</insert>
<select id = "selectUser" parameterType = "Integer" resultType = "user">
SELECT * FROM TB_USER WHERE id = #{id}
</select>
<update id = "modifyUser" parameterType = "user">
UPDATE TB_USER
SET name = #{name},sex = #{sex},age = #{age}
WHERE id = #{id}
</update>
<delete id = "removeUser" parameterType = "int">
delete from TB_USER WHERE id = #{id}
</delete>
</mapper>
5,编写测试类
做完上述配置之后,我们就可以开始做测试类来进行测试了。先上一段原始的;
package org.fkit.tst; 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;
import org.fkit.domain.User;
import org.fkit.factory.FKSqlSessionFactory; public class MyBatisTest { public static void main(String[] args) throws Exception{
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
User user = new User("admin","男",22);
session.insert("org.fkit.mapper.UserMapper.save",user);
session.commit();
session.close();
}
}
其中,SqlSession是MyBatis中作为操纵数据库的重要对象,相当于JDBC中的connection;而以上代码我们可以进行再封装;代码如下:
package org.fkit.factory; 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 FKSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory = null;
static{
try{
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
package org.fkit.tst; 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;
import org.fkit.domain.User;
import org.fkit.factory.FKSqlSessionFactory; public class MyBatisTest { public static void main(String[] args) throws Exception{
SqlSession session = FKSqlSessionFactory.getSqlSession();
User user = new User("admin","男",22);
session.insert("org.fkit.mapper.UserMapper.save",user);
session.commit();
session.close();
}
}
将读取配置文件的操作封装在一个Factory类中,这样就可以更加简便。
6,顺便附上数据库表结构: