使用mybatis,首先要配置环境(只需要配置一次)
步骤:
- 准备好mybatis-config.xml以及 mapper.xml文件的配置模板
- 在idea中,分别配置 mybatis-config.xml文件模板
mapper.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="">
</mapper>
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=""/>
<!-- 配置别名 -->
<typeAliases>
</typeAliases>
<!-- 配置mybatis的运行环境 -->
<environments default="development">
<environment id="development">
<!-- 采用的事务方式 -->
<transactionManager type="jdbc"/>
<!-- 配置数据源信息 -->
<dataSource type="pooled">
<property name="url" value=""/>
<property name="driver" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource=""/>
</mappers>
</configuration>
mybatis的使用方式,主要有两种形式:
-
方式1:传统方式(自己编写Dao类的代码,自己调用sql语句)
-
方式2:代理方式 (Dao层不用编写实现类,只需要定义一个接口,系统自动调用sql语句)
方式1:
步骤:
1、创建一个java工程
2、导入相关的jar
- mybatis.jar
- mysql.jar
3、生成主配置文件 mybatis-config.xml
4、编写db.properties文件,用于指定数据库连接信息
#数据库连接的基本信息
url=jdbc:mysql://localhost:3306/d91
driver=com.mysql.jdbc.Driver
user=root
pwd=root
5、在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="db.properties"/>
<!-- 配置别名 -->
<typeAliases>
</typeAliases>
<!-- 配置mybatis的运行环境 -->
<environments default="development">
<environment id="development">
<!-- 采用的事务方式 -->
<transactionManager type="jdbc"/>
<!-- 配置数据源信息 -->
<dataSource type="pooled">
<property name="url" value="${url}"/>
<property name="driver" value="${driver}"/>
<property name="username" value="${user}"/>
<property name="password" value="${pwd}"/>
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
</mappers>
</configuration>
6、编写实体类 (后面可以自动生成)----------要与数据表中的字段对应
package org.java.entity;
import java.io.Serializable;
public class Inf implements Serializable {
private Integer id;
private String name;
private Integer score;
@Override
public String toString() {
return "Inf{" +
"id=" + id +
", name='" + name + '\'' +
", score=" + score +
'}';
}
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 Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
7、编写映射文件,用于封装各种sql语句
注意:如果实体类的名称叫作: Inf
映射文件的名称一般叫作:InfMapper.xml
注意:xxxMapper.xml文件,一般我们会在 dao层中,与Dao类放在一起
<?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="inf">
</mapper>
8、将InfMapper.xml文件在主配置文件mybatis-config.xml进行注册
<!-- 注册映射文件 -->
<mappers>
<!-- 传统方式注册时,全类名之间要用/隔开 -->
<mapper resource="org/java/dao/InfMapper.xml"/>
</mappers>
9、在InfMapper.xml文件中,编写对应的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="inf">
<insert id="add" parameterType="org.java.entity.Inf">
insert into inf values(null,#{name},#{score})
</insert>
</mapper>
10、编写一个工具类,用于产生SqlSession ----------这个类,在后面的实际应用中不用写
@@@:mybatis对数据库的增删改查,都需要通过sqlSession完成
package org.java.util;
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 java.io.IOException;
import java.io.InputStream;
/**
* 工具类,产生SqlSession
*/
public class MyBatisUtil {
private static SqlSession ses;//它用于对数据库增删改查
public static SqlSession getSession(){
try {
//加载mybatis-config.xml获得输入流
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象,用于产生SqlSessionFactory
SqlSessionFactoryBuilder db = new SqlSessionFactoryBuilder();
//产生SqlSessionFactory
SqlSessionFactory factory = db.build(in);
//产生sqlSession
ses = factory.openSession();
//关闭流
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return ses;
}
}
11、编写Dao类
注意:Dao类命名习惯,以前我们叫作:XxxDao,在mybatis中一般叫作:XxxMapper
例如:实体类:Inf
Dao类: InfMapper
package org.java.dao;
import org.apache.ibatis.session.SqlSession;
import org.java.entity.Inf;
import org.java.util.MyBatisUtil;
/**
* 数据访问层
*/
public class InfMapper {
public void add(Inf f){
//1、获得sqlsession
SqlSession ses = MyBatisUtil.getSession();
//2、调用方法执行对应的sql语句
//ses.insert("哪一个命名空间.哪一个语句的id","参数");
ses.insert("inf.add",f);
//3、如果是执行增删改操作,需要提交事务
ses.commit();
//4、关闭sqlsession
ses.close();
}
}
12、测试类
package org.java.service;
import org.java.dao.InfMapper;
import org.java.entity.Inf;
public class InfService {
public static void main(String[] args) {
InfMapper mapper = new InfMapper();
Inf f = new Inf();
f.setName("jack");
f.setScore(90);
mapper.add(f);
}
}
示例:
编写InfMapper.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="inf">
<insert id="add" parameterType="org.java.entity.Inf">
insert into inf values(null,#{name},#{score})
</insert>
<select id="findById" parameterType="int" resultType="org.java.entity.Inf">
select * from inf where id=#{id}
</select>
<update id="update" parameterType="org.java.entity.Inf">
update inf set name=#{name},score=#{score} where id=#{id}
</update>
<select id="findAll" resultType="org.java.entity.Inf">
select * from inf
</select>
<delete id="del" parameterType="int">
delete from inf where id=#{id}
</delete>
</mapper>
编写InfMapper.java
package org.java.dao;
import org.apache.ibatis.session.SqlSession;
import org.java.entity.Inf;
import org.java.util.MyBatisUtil;
import java.util.List;
public class InfMapper {
public void add(Inf f){
SqlSession ses = MyBatisUtil.getSession();
ses.insert("inf.add",f);
ses.commit();
ses.close();
}
public Inf findById(int id){
SqlSession ses = MyBatisUtil.getSession();
Inf f = ses.selectOne("inf.findById",id);
ses.close();
return f;
}
public List<Inf> findAll(){
SqlSession ses = MyBatisUtil.getSession();
List<Inf> list = ses.selectList("inf.findAll");
ses.close();
return list;
}
public void update(Inf f){
SqlSession ses = MyBatisUtil.getSession();
ses.update("inf.update",f);
ses.commit();
ses.close();
}
public void del(int id){
SqlSession ses = MyBatisUtil.getSession();
ses.delete("inf.del",id);
ses.commit();
ses.close();
}
}
测试
package org.java.service;
import org.java.dao.InfMapper;
import org.java.entity.Inf;
import org.junit.Test;
import java.util.List;
public class InfService {
private InfMapper mapper = new InfMapper();
@Test
public void add(){
Inf f = new Inf();
f.setName("andy");
f.setScore(100);
mapper.add(f);
}
@Test
public void findById(){
Inf f = mapper.findById(1);
System.out.println(f);
}
@Test
public void update(){
Inf f = mapper.findById(1);
System.out.println("修改前:"+f);
f.setName("杰克");
mapper.update(f);
}
@Test
public void findAll(){
List<Inf> list = mapper.findAll();
for(Inf f:list){
System.out.println(f);
}
}
@Test
public void del(){
mapper.del(2);
}
}
方式2:
1、创建java工程
2、导入对应jar
- mybatis.jar
- mysql.jar
3、编写主配置文件: mybatis-config.xml
4、编写db.properties文件,封装数据库的基本连接信息
5、编写实体类
- Inf
6、编写Mapper接口
package org.java.dao;
import org.java.entity.Inf;
public interface InfMapper {
public void add(Inf f);
}
7、编写实体映射文件(作用:封装sql语句)
- InfMapper.xml
如果使用代理的方式配置mybatis,有如下要求:
- XxxxMapper.xml这个映射文件要与 XxxMapper接口放在同一个包中 (org.java.dao)
- 如果Dao层的接口名为:InfMapper,它的映射配置文件需要是:InfMapper.xml
- Mapper.xml文件中的namespace(命名空间)要指定为: Mapper接口的全路径(包名+接口名)
- Mapper接口的方法名称要与Mapper.xml文件语句的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" >
<!--命名空间的名字时InfMapper的全类名-->
<mapper namespace="org.java.dao.InfMapper">
<!--id的名字要跟InfMapper中方法的名字一致-->
<insert id="add" parameterType="inf">
insert into inf values(null,#{name},#{score})
</insert>
</mapper>
8、在mybatis-config.xml注册InfMapper接口
<mappers>
<mapper class="org.java.dao.InfMapper"/>
</mappers>
注意:代理的方式,注册的是Mapper接口,并且,小数点不用转义
9、编写MyBatisUtil类,用于获得sqlSession
10、编写Service类,进行测试
package org.java.service;
import org.apache.ibatis.session.SqlSession;
import org.java.dao.InfMapper;
import org.java.entity.Inf;
import org.java.util.MyBatilsUtil;
import org.junit.Test;
public class InfService {
@Test
public void add() {
//获得sqlSession
SqlSession ses = MyBatilsUtil.getSession();
//通过sqlsession获得它代理的接口
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf f = new Inf();
f.setName("christina");
f.setScore(58);
mapper.add(f);
//提交事务
ses.commit();
;
ses.close();
}
}
<insert id="add" parameterType="org.java.entity.Inf">
insert into inf values(null,#{name},#{score})
</insert>
@@@@:此处 parameterType="org.java.entity.Inf"表示,语句要接收的参数是一个Inf类型,如果每一条语句,参数
都声明为:包名+类,这样写会产生大量重复代码,一般给实体类起一个别名即可
指定别名的第一种方式:--------对指定的实体类设置别名
<typeAliases>
<typeAlias type="org.java.entity.Inf" alias="f"/>
</typeAliases>
<insert id="add" parameterType="f">
insert into inf values(null,#{name},#{score})
</insert>
不足之处:如果有100个实体类,这种方式,需要给每一个实体类分别指定别名
指定别名的第二方式:---------------对指定的包下面的所有实体类,自动生成别名
<typeAliases>
<package name="org.java.entity"/>
</typeAliases>
<insert id="add" parameterType="inf">
insert into inf values(null,#{name},#{score})
</insert>
默认生成类的别名的原则: 类名首字母小写
mybatis使用代理机制后,所有的Mapper接口需要在主配置文件mybatis-config.xml中注册
<mappers>
<mapper class="org.java.dao.InfMapper"/>
<mapper class="org.java.dao.StuMapper"/>
<mapper class="org.java.dao.TeacherMapper"/>
</mappers>
不足之处,如果有大量接口需要注册,这样方式,可读性不好
<mappers>
<package name="org.java.dao"/>
</mappers>
这种写法,表示:org.java.dao包下的接口,自动进行注册
-------------------------
一般在使用mybatis的时候,都建议,将它底层执行的sql语句显示出来,方便调试
我们只需要导入log4j.properties,mybatis在运行时,就可以显示底层sql语句,以前对应的参数
1、加入jar:
- log4j-1.2.13.jar, cglib-nodep-2.1_3.jar
2、加入log4j.properties
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
-------------------------
<insert id="add" parameterType="inf">
insert into inf values(null,#{name},#{score})
</insert>
@@@ parameterType="inf" 此代码,表示,参数是一个inf对象,如果参数是对象,占位符的名称必须是对象中
某一个属性名称
<select id="findById" parameterType="int" resultType="inf">
select * from inf where id=#{id}
</select>
@@@如果参数是一个具体的数据类型,那么它的占位符名称,可以任意指定
--------------------------
<select id="findAll" resultType="inf">
select * from inf
</select>
@@@:此处的 resultType="inf" 它的意思,只是用于描述,查询到每一条记录,封装成什么类型来返回,至于
返回的是对象还是集合是由语句决定
--------------------------------------------------------------
@@@@@@@此代码为错误代码
<select id="findByName" parameterType="String" resultType="inf">
select * from inf where name like '%#{name}%'
</select>
@@@@@@@@@@如果要模糊匹配,如果参数只有一个,并且是String类型,有如下要求:
- 参数占位符,必须写成: _parameter
- 在拼接参数时,不能使用#,而是要使用$
@@@@@@@@@@@此代码为正确代码---------第一种写法
<select id="findByName" parameterType="String" resultType="inf">
select * from inf where name like '%${_parameter}%'
</select>
@@@@@@@@@@@此代码为正确代码---------第二种写法
<select id="findByName" parameterType="String" resultType="inf">
select * from inf where name like concat('%',#{name},'%');
</select>
------------------------------------------------------------------
在查询时,xml文件中<这个符号,不能作为关系运行直接使用,这个符号必须转义才能使用
< <
<= <=
示例:
InfMapper.java
package org.java.dao;
import org.apache.ibatis.annotations.Param;
import org.java.entity.Inf;
import java.util.List;
import java.util.Map;
public interface InfMapper {
public void add(Inf f);
public Inf findById(int id);
public List<Inf> findAll();
public void del(int id);
public void update(Inf f);
public List<Inf> findByName(String name);
public List<Inf> findByName2(String name);
public List<Inf> findByScore(int score);
public List<Inf> findByScore2(Map map);
public List<Inf> findByCondition(Inf f);
public List<Inf> findByConditionMap(Map m);
public Map findMap(int id);
public List<Map> findMapList();
public int findCount();
//动态查询(不确定查询条件)
public List<Inf> findByDynamicCondition(Inf f);
//注意,如果有多个参数,注解不能省略
public List<Inf> findPage(@Param("startIndex") int startIndex,@Param("rows") int rows);
//注意,如果参数,只有一个,注解可省略
public Inf findById2(int id);
}
InfMapper.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="org.java.dao.InfMapper">
<insert id="add" parameterType="inf">
insert into inf values(null,#{name},#{score})
</insert>
<select id="findById" parameterType="int" resultType="inf">
select * from inf where id=#{id}
</select>
<select id="findAll" resultType="inf">
select * from inf
</select>
<update id="update" parameterType="inf">
update inf set name=#{name},score=#{score} where id=#{id}
</update>
<delete id="del" parameterType="int">
delete from inf where id=#{id}
</delete>
<select id="findByName" parameterType="String" resultType="inf">
select * from inf where name like '%${_parameter}%'
</select>
<select id="findByName2" parameterType="String" resultType="inf">
select * from inf where name like concat('%',#{name},'%')
</select>
<select id="findByScore" parameterType="int" resultType="inf">
select * from inf where score <=#{score}
</select>
<select id="findByScore2" parameterType="map" resultType="inf">
select * from inf where score between #{start} and #{end}
</select>
<select id="findByCondition" parameterType="inf" resultType="inf">
select * from inf where name like concat('%',#{name},'%') and score>=#{score}
</select>
<select id="findByConditionMap" parameterType="map" resultType="inf">
select * from inf where name like concat('%',#{name},'%') and score>=#{score}
</select>
<select id="findMap" parameterType="int" resultType="map">
select * from inf where id=#{id}
</select>
<select id="findMapList" resultType="map">
select * from inf
</select>
<select id="findByDynamicCondition" parameterType="inf" resultType="inf">
select * from inf
<where>
<if test="id!=null">
and id=#{id}
</if>
<if test="name!=null and name!=''">
and name like concat('%',#{name},'%')
</if>
<if test="score!=null">
and score>=#{score}
</if>
</where>
order by score desc
</select>
<select id="findCount" resultType="int">
select count(*) from inf
</select>
<select id="findPage" resultType="inf">
select * from inf limit #{startIndex},#{rows}
</select>
<select id="findById2" resultType="inf">
select * from inf where id=#{id}
</select>
</mapper>
测试:
package org.java.service;
import org.apache.ibatis.session.SqlSession;
import org.java.dao.InfMapper;
import org.java.entity.Inf;
import org.java.util.MyBatisUtil;
import org.junit.Test;
import sun.awt.IconInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class InfService {
@Test
public void add() {
Inf f = new Inf();
f.setName("boston");
f.setScore(100);
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
mapper.add(f);
ses.commit();
ses.close();
}
@Test
public void findById() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf inf = mapper.findById(6);
System.out.println(inf);
ses.close();
}
@Test
public void findAll() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
List<Inf> list = mapper.findAll();
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void update() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf inf = mapper.findById(1);
inf.setName("jack");
mapper.update(inf);
ses.commit();
ses.close();
}
@Test
public void findName() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
List<Inf> list = mapper.findByName2("c");
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findScore() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
List<Inf> list = mapper.findByScore(90);
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findScore2() {
Map map = new HashMap();
map.put("start", 60);
map.put("end", 92);
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
List<Inf> list = mapper.findByScore2(map);
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findByCondition() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf k = new Inf();
k.setName("c");
k.setScore(60);
List<Inf> list = mapper.findByCondition(k);
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findByConditionMap() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Map map = new HashMap();
map.put("name", "c");
map.put("score", 60);
List<Inf> list = mapper.findByConditionMap(map);
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findMap() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Map map = mapper.findMap(1);
System.out.println(map);
ses.close();
}
@Test
public void findMapList() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
List<Map> list = mapper.findMapList();
for (Map map : list) {
System.out.println(map);
}
ses.close();
}
@Test
public void findByDynamicCondition() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf k = new Inf();
k.setScore(60);
k.setName("c");
k.setId(1);
List<Inf> list = mapper.findByDynamicCondition(k);
for (Inf f : list) {
System.out.println(f);
}
ses.close();
}
@Test
public void findCount() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
int count = mapper.findCount();
System.out.println(count);
ses.close();
}
@Test
public void findPage() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
//开始下标
int page = 2;
int rows = 3;
int startIndex = (page-1)*rows;
List<Inf> list = mapper.findPage(startIndex, rows);
for(Inf f:list){
System.out.println(f);
}
ses.close();
}
@Test
public void findById2() {
SqlSession ses = MyBatisUtil.getSession();
InfMapper mapper = ses.getMapper(InfMapper.class);
Inf inf = mapper.findById2(6);
System.out.println(inf);
ses.close();
}
}