之前写了Ibatis,为了做个对比,今天写写MyBatis:
一、基于xml映射形式:
1.总配置文件Configuration.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="com/mymy/jdbc.properties"> <property name="username" value="root"/> <!-- 会被jdbc.properties中的值覆盖 --> <property name="password" value="123"/> </properties> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,是否开启懒加载模式,true:关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="false" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> <setting name="useGeneratedKeys" value="true" /> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="FULL" /> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="BATCH" /> <!-- 数据库超过25000秒仍未响应则超时 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <!-- 全局别名 --> <typeAliases> <typeAlias type="com.mymy.bean.User" alias="User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!-- xml形式的映射 --> <mapper resource="com/mymy/bean/User.xml" /> <!-- 注解形式的映射 <mapper class="com.mymy.dao.UserDao" /> --> </mappers> </configuration>2.数据库配置文件jdbc.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatisdb
username=root
password=123
3 User实体类:
package com.mymy.bean;
public class User {
private int id;
private String userName;
private int userAge;
private String userAddress;
public User() { }
public User(String userName, int userAge,String userAddress) {
this.userName = userName;
this.userAge = userAge;
this.userAddress = userAddress;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
4.UserMapper.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="User" > <resultMap type="User" id="userResultMap"> <result column="id" property="id" /> <result column="user_name" property="userName" /> <result column="user_age" property="userAge" /> <result column="user_address" property="userAddress" /> </resultMap> <select id="selectOneUser" parameterType="int" resultType="User" resultMap="userResultMap"> select * from t_user where id = #{id} </select> <insert id="insertUser" parameterType="User" > INSERT INTO t_user (user_name,user_age,user_address) VALUES(#{userName},#{userAge},#{userAddress}) </insert> <delete id="deleteUser" parameterType="Integer"> delete from t_user where id = #{id} </delete> <update id="updateUser" parameterType="User" > UPDATE t_user t SET t.user_name=#{userName},t.user_age=#{userAge} WHERE t.id=#{id} </update> </mapper>
5.MyBatisTest 测试类:
package com.test;
import java.io.IOException;
import java.io.Reader;
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 com.model.User;
public class MyBatisTest {
private static SqlSessionFactory fa = null;
private static Reader reader = null;
static{
try {
reader = Resources.getResourceAsReader("Configuration.xml");
fa = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return fa;
}
public static void main(String[] args) {
SqlSession session = getSqlSessionFactory().openSession();
try{
// * 增
// User user = new User("abc",11,"asdf");
// session.insert("User.insertUser",user);
// * 删
// session.delete("User.deleteUser", 7);
/*
* 改
*/
User user = new User("abc",13,"asdf");
user.setId(6);
session.update("updateUser",user);
/*
* 查
*/
// User user = session.selectOne("User.selectOneUser",1);
// System.out.println(user.getUserName()+":"+user.getUserAge());
}finally{
session.commit();
session.close();
}
}
}
6.项目结构:
二、基于注解形式:
1.和xml形式的区别在于总配置文件Configuration.xml中的<mapper class="com.mymy.dao.UserDao" />指定接口,具体接口如下:
2.UserDao接口
package com.mymy.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.mymy.bean.User;
public interface UserDao {
//字段都列出来是为了解决[数据库字段]和[实体类中属性]不一致的问题
@Select("select id as id, user_name as userName,user_age as userAge ,user_address as userAddress from t_user where id =#{id}")
public User findUserById(int id);
@Update("update t_user t set t.user_name=#{userName} , t.user_age=#{userAge} , t.user_address = #{userAddress} where t.id=#{id}")
public void updateUser(User user);
@Insert("insert into t_user (user_name,user_age,user_address) values (#{userName},#{userAge},#{userAddress})" )
public void addUser(User user);
@Delete("delete from t_user where id = #{id}")
public void deleteUserById(int id);
@Select("select id as id, user_name as userName,user_age as userAge ,user_address as userAddress from t_user")
public List<User> findUserList();
}
3.测试类:
package com.mymy.test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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 com.mymy.bean.User;
import com.mymy.dao.UserDao;
public class MyBatisTest {
private static SqlSessionFactory fa = null;
private static Reader reader = null;
static{
try {
reader = Resources.getResourceAsReader("Configuration.xml");
fa = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getFactory(){
return fa;
}
public static void main(String[] args) {
SqlSession session = getFactory().openSession();
try{
UserDao userdao = session.getMapper(UserDao.class);
/* 查
User u = userdao.findUserById(4);
System.out.println(u.getUserName()+"/"+u.getUserAge());
*/
//增
//userdao.addUser(new User("hello",16,"sh"));
//删
//userdao.deleteUserById(8);
/* 改
User u = new User("kitty",10,"japan");
u.setId(1);
userdao.updateUser(u);
*/
List<User> userList = userdao.findUserList();
for (User u : userList) {
System.out.println(u.getId());
System.out.println(u.getUserName());
System.out.println(u.getUserAge());
System.out.println(u.getUserAddress());
System.out.println("================");
}
session.commit();
}finally{
session.close();
}
}
}
4.项目解结构:
在总配置文件注册xml或者注解所在的接口,得到SessionFactory ->得到session
1.通过session的方法(insert、update、delete、selectOne等)+ namespace+sql的id ,进行操作
2.通过session的gaetMapper(接口.class) 得到接口的句柄,从而操作接口内的方法。