mybatis
ibatis 亲爹 apache 后爹 google 后后爹github
开源的持久层框架
jdbc 代码繁琐 手写sql 速度快,性能好 就是麻烦
编程步骤
1、导包
2、添加mybatis配置文件
3、写实体类
4、写映射文件,修改配置文件,指定英文文件的位置
5、调用mybatis 提供的API SqlSession 提供的方法来访问数据库
1、导包
mybatis
mysql
2、配置文件
<?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> <!-- 环境:配置mybatis的环境 --> <environments default="environment"> <!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 --> <environment id="environment"> <!-- 事务管理器 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据源 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://172.29.12.158:3306/test?useUnicode=true&characterEncoding=utf8"/> <property name="username" value="zongxuan"/> <property name="password" value="zongxuan"/> </dataSource> </environment> </environments> <!-- 映射器:指定映射文件或者映射类 --> <mappers> <mapper resource="entity/MepMapper.xml"/> </mappers> </configuration>
3、实体类的属性名与表的字段表要求一样 大小写无所谓
package entity;
public class Emp {
private Integer id;
private String name;
private Double 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 Double getAge() {
return age;
}
public void setAge(Double age) {
this.age = age;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
4、写实体类
<?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="test"> <!-- id 唯一 parameterType 参数类型 #{} 实体类的属性 --> <insert id="save" parameterType="entity.Emp"> INSERT INTO emp2(name,age) VALUES(#{name},#{age}) </insert> <!-- resultType:返回结果的类型 最终的 --> <select id="findAll" resultType="entity.Emp"> SELECT * FROM emp2 </select> <select id="findById" parameterType="int" resultType="entity.Emp"> SELECT * FROM emp2 WHERE id=#{id} </select> <update id="modify" parameterType="entity.Emp"> UPDATE emp2 SET name=#{name},age=#{age} WHERE id=#{id} </update> <delete id="delete" parameterType="int"> DELETE FROM emp2 WHERE id=#{id} </delete> </mapper>
5、调用mybatis
package testCase;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import entity.Emp;
public class TestMybats {
private SqlSession ss ;
@Before
public void init() {
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
SqlSessionFactory ssf = ssfb.build(TestMybats.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));
ss = ssf.openSession();
}
@Test
public void t1() {
Emp emp = new Emp();
emp.setName("李四");
emp.setAge(new Double("22"));
ss.insert("test.save",emp);
ss.commit();
ss.close();
}
@Test
public void t2() {
List<Emp> emps = ss.selectList("test.findAll");
System.out.println(emps);
ss.close();
}
@Test
public void t3() {
Emp emp = ss.selectOne("test.findById",4);
System.out.println(emp);
ss.close();
}
@Test
public void t4() {
Emp emp = ss.selectOne("test.findById",4);
emp.setName("王五");
ss.update("test.modify",emp);
ss.commit();
ss.close();
}
@Test
public void t5() {
ss.delete("test.delete", 1);
ss.commit();
ss.close();
}
}
返回Map类型的结果
mybatis 会将查询结果先封装到一个map对象里面 字段名作为key 字段值作为value
然后再将map对象中的数据添加到实体对象里面
<select id="findById2" parameterType="int" resultType="map"> SELECT * FROM dept WHERE id=#{id} </select>
@Test
public void t6() {
Map data = ss.selectOne("dept.findById2",3);
System.out.println(data);
System.out.println(data.get("dname"));
ss.close();
}
属性名和字段名不一样
1、在mybatis 映射文件SQL 中使用别名
2、使用ResultMap
1
2、
CREATE TABLE `emp2` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
package entity;
public class Emp2 {
private Integer emapNo;
private String ename;
private Double age;
public Integer getEmapNo() {
return emapNo;
}
public void setEmapNo(Integer emapNo) {
this.emapNo = emapNo;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Double getAge() {
return age;
}
public void setAge(Double age) {
this.age = age;
}
@Override
public String toString() {
return "Emp2 [emapNo=" + emapNo + ", ename=" + ename + ", age=" + age + "]";
}
}
<!-- 使用ResultMap 解决表的字段名和实体类的属性名不一致的情况 --> <!-- 处理表的字段名和实体类的属性名的对应关系 --> <resultMap type="entity.Emp2" id="emp2Map"> <result property="ename" column="name" /> <result property="emapNo" column="id" /> </resultMap> <select id="findById2" parameterType="int" resultMap="emp2Map"> SELECT * FROM emp2 WHERE id=#{id} </select> @Test public void t6() { Emp2 emp = ss.selectOne("test.findById2",3); System.out.println(emp); ss.close(); }
Mapper 映射器
符合映射文件的接口
mybatis 会自动实现一个符合该接口要求的对象
要求:
a、接口方法的名称与映射中的sql的id要一样
b、方法的参数类型要与映射文件中的parameterType一致
c、方法的飞回类型要与映射文件当中的resultType一致
映射文件的命名空间namespace要等于Mapper映射器的全限定名
<?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> <!-- 环境:配置mybatis的环境 --> <environments default="environment"> <!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 --> <environment id="environment"> <!-- 事务管理器 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据源 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://172.29.12.158:3306/test?useUnicode=true&characterEncoding=utf8"/> <property name="username" value="zongxuan"/> <property name="password" value="zongxuan"/> </dataSource> </environment> </environments> <!-- 映射器:指定映射文件或者映射类 --> <mappers> <mapper resource="entity/EmpMapper.xml"/> </mappers> </configuration>
package com.stevezong.mybatis.entity.dao;
import java.util.List;
import java.util.Map;
import entity.Emp;
import entity.Emp2;
/**
* Mapper映射器 就是一个接口
* @author steve
*
*/
public interface EmpDAO {
void save(Emp emp);
List<Emp> findAll();
Emp findById(int id);
void delete(int id);
void modify(Emp emp);
Emp2 findById2(int id);
}
<?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.stevezong.mybatis.entity.dao.EmpDAO"> <!-- id 唯一 parameterType 参数类型 #{} 实体类的属性 --> <insert id="save" parameterType="entity.Emp"> INSERT INTO emp2(name,age) VALUES(#{name},#{age}) </insert> <!-- resultType:返回结果的类型 最终的 --> <select id="findAll" resultType="entity.Emp"> SELECT * FROM emp2 </select> <select id="findById" parameterType="int" resultType="entity.Emp"> SELECT * FROM emp2 WHERE id=#{id} </select> <update id="modify" parameterType="entity.Emp"> UPDATE emp2 SET name=#{name},age=#{age} WHERE id=#{id} </update> <delete id="delete" parameterType="int"> DELETE FROM emp2 WHERE id=#{id} </delete> <!-- 使用ResultMap 解决表的字段名和实体类的属性名不一致的情况 --> <!-- 处理表的字段名和实体类的属性名的对应关系 --> <resultMap type="entity.Emp2" id="emp2Map"> <result property="ename" column="name" /> <result property="emapNo" column="id" /> </resultMap> <select id="findById2" parameterType="int" resultMap="emp2Map"> SELECT * FROM emp2 WHERE id=#{id} </select> </mapper>
package testCase;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.stevezong.mybatis.entity.dao.EmpDAO;
import entity.Emp;
import entity.Emp2;
public class TestCase {
private SqlSession ss;
@Before
public void init() {
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
SqlSessionFactory ssf = ssfb.build(TestCase.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));
ss = ssf.openSession();
}
@Test
public void t1() {
/**
* getMapper 方法返回一个符合Mapper映射器(EmpDAO)要求的对象
*
*/
EmpDAO dao = ss.getMapper(EmpDAO.class);
Emp emp = new Emp();
emp.setName("王八");
emp.setAge(new Double(22));
dao.save(emp);
ss.commit();
List<Emp> emps = dao.findAll();
System.out.println(emps);
Emp emp2 =dao.findById(4);
System.out.println(emp2);
dao.delete(2);
ss.commit();
Emp emp3 = new Emp();
emp3.setName("丽丽");
emp3.setAge(new Double(88));
emp3.setId(10);
dao.modify(emp3);
ss.commit();
Emp2 emp4 = dao.findById2(3);
System.out.println(emp4);
ss.close();
}
}
spring 集成 mybatis
1、导包
spring-webmvc
mybatis
mybatis-spring
spring-jdbc
mysql
dbcp(c3p0)
2、添加spring的配置文件
mybatis 的配置信息可以添加到spring的配置文件中
3、实体类
entity
4、映射文件
XML
5、Mapper映射器
DAO接口
6、在spring 的配置文件当中,添加MapperScannerConfigurer bean 该bean 负责条用SqlSession的getMapper方法
创建符合Mapper映射器要求的对象,
该bean会将这个对象添加到spring容器里面(默认额id 是首字母小写之后的接口名,也可以在Mapper使用@Rerspository来设定id)
1、
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.stevezong</groupId> <artifactId>mybataiszx</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>commons-DBCP</groupId> <artifactId>commons-DBCP</artifactId> <version>1.4</version> </dependency> </dependencies> </project>
2、
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- mysql 信息 --> <util:properties id="dbInfo"> <prop key="user">zongxuan</prop> <prop key="password">zongxuan</prop> <prop key="url">jdbc:mysql://172.29.12.158:3306/test?useUnicode=true&characterEncoding=utf8 </prop> <prop key="driver">com.mysql.jdbc.Driver</prop> <prop key="initialSize">10</prop> <prop key="maxActive">500</prop> </util:properties> <!-- 配置连接池 --> <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="#{dbInfo.driver}"></property> <property name="url" value="#{dbInfo.url}"></property> <property name="username" value="#{dbInfo.user}"></property> <property name="password" value="#{dbInfo.password}"></property> <property name="initialSize" value="#{dbInfo.initialSize}"></property> <property name="maxActive" value="#{dbInfo.maxActive}"></property> </bean> <!-- 配置SqlSessionFactoryBean mybatis-spring包中 spring 集成mybatis 不在需要mybatis 的配置文件,(使用SqlSessionFactoryBean来代替mybatis的配置文件) --> <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入连接池, 不再使用mybatis 自带的连接池,而是使用spring管理的连接池 --> <property name="dataSource" ref="ds"></property> <property name="mapperLocations" value="classpath:entity/*.xml"></property> </bean> <!-- 配置MapperScannerConfigurer 负责扫描指定包下面的所有的Mapper映射器然后生成符合这些映射器要求的对象 其实,就是调用SqlSession的getMapper方法 另外,还会将这个对象添加到spring容器里面 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定Mapper映射器所在的包 --> <property name="basePackage" value="dao"></property> <!-- 只扫描特定的接口 自己开发注解 自动扫描包下所有接口 遇到带注解标记的将对应对象注册 不加不注解 不会注册 --> <property name="annotationClass" value="annotations.MyBatisRepository"></property> </bean> </beans>
3
package entity;
public class Emp {
private Integer id;
private String name;
private Double 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 Double getAge() {
return age;
}
public void setAge(Double age) {
this.age = age;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
4
<?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="dao.EmpDAO"> <!-- id 唯一 parameterType 参数类型 #{} 实体类的属性 --> <insert id="save" parameterType="entity.Emp"> INSERT INTO emp2(name,age) VALUES(#{name},#{age}) </insert> <!-- resultType:返回结果的类型 最终的 --> <select id="findAll" resultType="entity.Emp"> SELECT * FROM emp2 </select> <select id="findById" parameterType="int" resultType="entity.Emp"> SELECT * FROM emp2 WHERE id=#{id} </select> <update id="modify" parameterType="entity.Emp"> UPDATE emp2 SET name=#{name},age=#{age} WHERE id=#{id} </update> <delete id="delete" parameterType="int"> DELETE FROM emp2 WHERE id=#{id} </delete> <!-- 使用ResultMap 解决表的字段名和实体类的属性名不一致的情况 --> <!-- 处理表的字段名和实体类的属性名的对应关系 --> <resultMap type="entity.Emp2" id="emp2Map"> <result property="ename" column="name" /> <result property="emapNo" column="id" /> </resultMap> <select id="findById2" parameterType="int" resultMap="emp2Map"> SELECT * FROM emp2 WHERE id=#{id} </select> </mapper>
5
package dao;
import java.util.List;
import java.util.Map;
import annotations.MyBatisRepository;
import entity.Emp;
import entity.Emp2;
/**
* Mapper映射器 就是一个接口
* @author steve
*
*/
@MyBatisRepository
public interface EmpDAO {
void save(Emp emp);
List<Emp> findAll();
Emp findById(int id);
void delete(int id);
void modify(Emp emp);
Emp2 findById2(int id);
}
package annotations;
public @interface MyBatisRepository {
}
6
package test;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.EmpDAO;
import entity.Emp;
public class TestCase {
private ApplicationContext ac;
private EmpDAO dao ;
@Before
public void init() {
ac = new ClassPathXmlApplicationContext("applicationContext.xml");
dao =ac.getBean("empDAO",EmpDAO.class);
}
@Test
public void t1() {
List<Emp> emps = dao.findAll();
System.out.println(emps);
}
@Test
public void t2() {
Emp emp = dao.findById(5);
System.out.println(emp);
}
}