参考:唐浩荣–Mybatis3详解(二)----Mybatis的第一个入门实例
前提条件
- 一个数据库
- 一个maven项目
- maven项目中配好依赖
- 创建一个实体类,实体类中有若干属性
- 然后进入mybatis部分
创建maybatis全局配置文件
在resources目录下创建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 >
<environments default="develop">
<environment id="develop">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/younghedb?characterEncoding=utf8"/>
<property name="username" value="数据库用户"/>
<property name="password" value="密码"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmpMapper.xml"></mapper>
</mappers>
</configuration>
编写SQL映射配置文件(mapper.xml文件)
仍旧是在resources下创建一个mapper.xml文件,mybatis中所有数据库的操作都会基于该映射文件配置的SQL语句。 mapper.xml文件中的属性的作用
相关属性 | 描述 |
---|
namespace | namespace是mapper配置文件的唯一标识,不同Mapper文件的namespace值应该保证唯一,在程序中通过[ namespace + id ]定位到要执行哪一条SQL语句 | id | sql映射语句的唯一标识,sql语句封装到mappedStatement对象中,mappedStatement对象的标识 | parameterType | 指定输入参数的类型 | resultType | 指定输出结果的类型,mybatis将查询结果的记录(行),映射成resultType指定的类型的对象,就是上一篇中,对象和记录的映射。如果有多条数据,则分别进行映射,并把对象放到List容器中。 | #{value} | #{value}表示SQL语句的占位符,会自动进行java类型和jdbc类型转换,相当于jdbc中的“?”,不能空。 | ${value} | 表示拼接SQL字符串,将接收到的参数在不进行jdbc类型转换的情况下拼接在SQL语句中。 | #{value}和${value}的区别 | ${}是Properties文件中的变量占位符,用于标签属性值和SQL内部,属于静态文本替换,#{}是SQL参数占位符,mybaits会将#{}替换成?,在sql执行前用preparedStatement的参数设置方法,按序给sql的?号占位符设置参数值。 |
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="EmpMapper">
<select id="findAll" resultType="cn.itpc.pojo.Emp">
-- select就是数据库查询语句的标签 resultType就是返回值类型,写法是包名加类名 而对应的test文件中就是写namespace.id
select * from emp
</select>
<update id="insert">
insert into emp value (null,"赵云","保镖",6000)
</update>
<update id="update">
update emp set job="花滑运动员",salary=400000 where name="羽生结弦"
</update>
<delete id="delete">
delete from emp where name ="张三"
</delete>
<select id="findById" resultType="cn.itpc.pojo.Emp">
select * from emp where id=#{id}
</select>
<update id="insert2">
insert into emp values (null,#{name},#{job},#{salary})
</update>
<update id="update2">
update emp set job=#{job},salary=#{salary} where name=#{name}
</update>
<update id="delete2">
delete from emp where id=#{id};
</update>
<select id="findAll2" resultType="cn.itpc.pojo.Emp">
select ${cols} from emp
</select>
<select id="findAll3" resultType="cn.itpc.pojo.Emp">
select * from emp where name like '%${name}%'
-- ${}是符号 % 表示前面或后面任意字符或字符串
</select>
<select id="findAll4" resultType="cn.itpc.pojo.Emp">
select * from emp where name like #{name}
</select>
</mapper>
加载映射文件
创建的mapper.xml文件添加到全局配置文件下 上面的已经加过了
指定映射配置文件mapper.xml的位置
<mappers>
<mapper resource="EmpMapper.xml"></mapper>
</mappers>
导入日志文件
在resources目录中创建log4j.properties文件,并且导入如下配置
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
编写测试代码
最后创建一个测试类
package cn.itpc.mybaitis;
import cn.itpc.pojo.Emp;
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.junit.Before;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//练习 查询emp表中所有的员工,返回一个List<emp>集合
public class TestMyBatis01 {
// SqlSession session;
//
// @Before
// public void init() throws IOException {
// InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
// SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
// session = fac.openSession();
//
// }
//1、读取mybatis的核心配置文件(mybatis-config.xml)
//2、通过配置信息获取一个SqlSessionFactory工厂对象
//3、通过工厂获取一个SqlSession对象
//4、通过namespace+id找到要执行的sql语句并执行
//5、输出结果
@Test
public void findAll() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
List<Emp> list = session.selectList("EmpMapper.findAll");
for (Emp e:list){
System.out.println(e);
}
}
@Test
public void testInsert() throws IOException {
//执行sql语句,返回执行结果
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.update("EmpMapper.insert");
//提交事务
session.commit();
System.out.println("影响的行数:"+row);
}
@Test
public void testupdate() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.update("EmpMapper.update");
session.commit();
}
@Test
public void testdelete() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.delete("EmpMapper.delete");
session.commit();
}
@Test
public void testFindById() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
Emp emp=session.selectOne("EmpMapper.findById");
System.out.println(emp);
}
@Test
public void testInsert2() throws IOException {
Emp emp=new Emp();
emp.setName("张飞");
emp.setJob("工程师");
emp.setSalary(12334.0);
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row = session.update("EmpMapper.insert2",emp);
session.commit();
System.out.println("影响的行数:"+row);
}
@Test
public void testupdate2() throws IOException {
Emp emp=new Emp();
emp.setName("张飞");
emp.setJob("架构师");
emp.setSalary(2222.2);
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.update("EmpMapper.update2",emp);
session.commit();
System.out.println("影响的行数"+row);
}
@Test
public void testInsert3() throws IOException {
Map map=new HashMap<>();
map.put("name","曹操");
map.put("job","总裁办公室");
map.put("salary","20000");
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.update("EmpMapper.insert2",map);
session.commit();
System.out.println("影响行数"+row);
}
@Test
public void testDelete2() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
int row=session.update("EmpMapper.delete2",5);
session.commit();
System.out.println("影响行数"+row);
}
@Test
public void testFindAll2() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
Map map=new HashMap();
map.put("cols","id,name");
// map.put("cols","id,name,jpb,salary");
List<Emp> list=session.selectList("EmpMapper.findAll2",map);
for (Emp e:list){
System.out.println(e);
}
}
@Test
public void testFindAll3() throws IOException {
Map map=new HashMap();
map.put("name","云");
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
List<Emp> list=session.selectList("EmpMapper.findAll3",map);
for (Emp e:list){
System.out.println(e);
}
}
@Test
public void testFindAll4() throws IOException {
Map map=new HashMap();
map.put("name","%生%");
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
SqlSession session = fac.openSession();
List<Emp> list=session.selectList("EmpMapper.findAll4",map);
for(Emp e:list){
System.out.println(e);
}
}
}
|