前面已经和大家讲过我们配置resources 等东西,大家可以看上个文章里的代码,这里就不演示配置了。
database.properties 文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/text?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
username=root
password=123.com
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">
<!--mybatis核心配置文件-->
<configuration>
<!--引入包含数据库参数的文件 database.properties -->
<properties resource="database.properties"/>
<typeAliases>
<package name="com.bdqn.pojo"/>
</typeAliases>
<!--配置Mybatis框架的运行环境-->
<environments default="ss">
<environment id="ss">
<!--配置事物管理 使用JDBC事物 ,由应用自行管理事务-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源 默认POOLED: Mybatis提供的数据源, JNDI: JNDI数据源-->
<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>
<!--配置需要引用的sql映射文件-->
<mappers>
<!--
<mapper resource="com/bdqn/dao/UserMapper.xml"></mapper>
-->
<package name="com.bdqn.dao"/>
</mappers>
</configuration>
创建业务逻辑层
创建好UserMapper.xml
创建UserMapper接口
创建好实体类User
创建工具类Userutli
package com.bdqn;
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.File;
import java.io.IOException;
import java.io.InputStream;
public class Userutli {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession sqlSession(){
return sqlSessionFactory.openSession(); //关闭自动提交开启事务
}
public void setSqlSessionFactory(SqlSession sqlSession){
if (sqlSession!=null){
sqlSession.close();
}
}
}
创建测试类
映射练习
使用模糊查询查找数据
UserMapper 接口里面写模糊查询的方法
package com.bdqn.dao;
import com.bdqn.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserName(String name); //模糊查询
}
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="com.bdqn.dao.UserMapper">
<select id="getUserName" resultType="user" parameterType="string">
select * from user where username like CONCAT('%',#{username},'%')
</select>
</mapper>
编写测速类test01
package com.bdqn.test;
import com.bdqn.dao.UserMapper;
import com.bdqn.pojo.User;
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.Test;
import java.io.InputStream;
import java.util.List;
public class test01 {
@Test
public void test01() throws Exception{
//读取Mybatis核心配置文件
String rr="mybatis-config.xml";
//获取mybatis-config.xml的输入流
InputStream is = Resources.getResourceAsStream(rr);
//使用sqlSessionFactortBuilder读取配置文件并构建
// SqlSessionFactory 实例
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
//创建SqlSession实例\
SqlSession sqlSession=sessionFactory.openSession();
List<User> userName = sqlSession.getMapper(UserMapper.class).getUserName("aaa");
for (User user : userName) {
System.out.println(user.getUserid()+"\t"+user.getUsername());
}
}
}
使用User类的对象来进行模糊查询
编写UserMapper接口
package com.bdqn.dao;
import com.bdqn.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserName(String name); //模糊查询
User getUserr(User user); //根据User对象来进行查询
}
编写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="com.bdqn.dao.UserMapper">
<select id="getUserName" resultType="user" parameterType="string">
select * from user where username like CONCAT('%',#{username},'%')
</select>
<select id="getUserr" resultType="user" parameterType="user">
select *from user where userid=#{userid} and username=#{username}
</select>
</mapper>
编写测试类
@Test
//根据User查询
public void test02() throws Exception{
//创建User对象
User user=new User();
user.setUserid(1);
user.setUsername("eee");
//读取Mybatis核心配置文件
String rr="mybatis-config.xml";
//获取mybatis-config.xml的输入流
InputStream is = Resources.getResourceAsStream(rr);
//使用sqlSessionFactortBuilder读取配置文件并构建
// SqlSessionFactory 实例
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
//创建SqlSession实例\
SqlSession sqlSession=sessionFactory.openSession();
User userNamee = sqlSession.getMapper(UserMapper.class).getUserr(user);
System.out.println(userNamee.getUserid()+"\t"+userNamee.getUsername());
}
将查询条件封装成MAP对象作为入参实现模糊查询
编写UserMapper接口
package com.bdqn.dao;
import com.bdqn.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserName(String name); //模糊查询
User getUserr(User user); //根据User对象来进行查询
User getMAp(@Param("id") int id,@Param("name") String name); //使用MAP封装数据进行查询
}
编写测试类
@Test
//根据MAp查询
public void test03() throws Exception{
//读取Mybatis核心配置文件
String rr="mybatis-config.xml";
//获取mybatis-config.xml的输入流
InputStream is = Resources.getResourceAsStream(rr);
//使用sqlSessionFactortBuilder读取配置文件并构建
// SqlSessionFactory 实例
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
//创建SqlSession实例\
SqlSession sqlSession=sessionFactory.openSession();
User userNamee = sqlSession.getMapper(UserMapper.class).getMAp(1,"eee");
System.out.println(userNamee.getUserid()+"\t"+userNamee.getUsername());
}
利用嵌套结果映射 association
创建一个新的实体类 Student
package com.bdqn.pojo;
import java.util.List;
public class Student {
private int studentN;
private int grai;
private String studentme;
public int getStudentN() {
return studentN;
}
public void setStudentN(int studentN) {
this.studentN = studentN;
}
public int getGrai() {
return grai;
}
public void setGrai(int grai) {
this.grai = grai;
}
public String getStudentme() {
return studentme;
}
public void setStudentme(String studentme) {
this.studentme = studentme;
}
}
在创建一个Student接口
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import java.util.List;
public interface StudentMapper {
List<Student> getsss(); //定义一对多
}
在创建一个StudentMapper.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="com.bdqn.dao.StudentMapper">
<resultMap id="student" type="student">
<id property="studentN" column="studentNo"></id> <!--//主键-->
<result property="grai" column="gradeId"></result> <!--property 实体类 column 数据库-->
<result property="studentme" column="studentname"></result>
</resultMap>
<select id="getsss" resultMap="student" >
select * from student
</select>
</mapper>
编写测试类
@Test
//根据嵌套结果映射
public void test04() throws Exception{
//读取Mybatis核心配置文件
String rr="mybatis-config.xml";
//获取mybatis-config.xml的输入流
InputStream is = Resources.getResourceAsStream(rr);
//使用sqlSessionFactortBuilder读取配置文件并构建
// SqlSessionFactory 实例
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
//创建SqlSession实例\
SqlSession sqlSession=sessionFactory.openSession();
List<Student> getsss = sqlSession.getMapper(StudentMapper.class).getsss();
for (Student student : getsss) {
System.out.println(student.getStudentN()+"\t"+student.getGrai()+"\t"+student.getStudentme());
}
}
多对一collection
编写StudentMapper接口
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import java.util.List;
public interface StudentMapper {
List<Student> getsss(); //定义一对多
List<Student> getStudent();//多对一
}
编写StudentMapper.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="com.bdqn.dao.StudentMapper">
<resultMap id="student" type="student">
<id property="studentN" column="studentNo"/>
<result property="grai" column="gradeId"/>
<result property="studentme" column="studentName"/>
<!-- <association property="grade" javaType="grade">
<id property="id" column="id"/>
<result property="name" column="name"/>-->
<collection property="gradeList" ofType="grade">
<id property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
<select id="getsss" resultMap="student" >
select * from student
</select>
<select id="getStudent" resultMap="student">
SELECT * FROM student AS s , grade AS g WHERE s.`gradeId` = g.id
</select>
</mapper>
编写测试类
@Test
//根据嵌套结果映射
public void test05() throws Exception{
//读取Mybatis核心配置文件
String rr="mybatis-config.xml";
//获取mybatis-config.xml的输入流
InputStream is = Resources.getResourceAsStream(rr);
//使用sqlSessionFactortBuilder读取配置文件并构建
// SqlSessionFactory 实例
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is);
//创建SqlSession实例\
SqlSession sqlSession=sessionFactory.openSession();
Student student1 = sqlSession.getMapper(StudentMapper.class).getStudent().get(0);
System.out.println(student1.getStudentN()+"\t"+student1.getGrai()+"\t"+student1.getStudentme());
}
Mybatis 框架的增删改 操作
查询全部的方法
在StudentMapper 接口创建查询全部的方法
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
//查询全部
List<Student> getAll();
}
在StudentMapper.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="com.bdqn.dao.StudentMapper">
<!--//查询全部的方法-->
<select id="getAll" resultType="student" useCache="true" >
select * from student
</select>
</mapper>
在StudentTest测试类进行测试
package com.bdqn.test;
import com.bdqn.dao.StudentMapper;
import com.bdqn.pojo.Student;
import com.bdqn.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class StudentTest {
@Test
public void test01() throws Exception{
SqlSession sqlSession = MybatisUtil.creatSqlSession();
List<Student> studentList = sqlSession.getMapper(StudentMapper.class).getAll();
System.out.println("序号\t姓名\t密码");
for (Student student : studentList) {
System.out.println(student.getId()+"\t"+student.getUserName()+"\t\t"+student.getUserPwd());
}
}
实现结果
添加的方法
在StudentMapper 接口创建添加的方法
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
//查询全部
List<Student> getAll();
//添加学生的方法
int insertStudent(Student student);
}
在StudentMapper.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="com.bdqn.dao.StudentMapper">
<!--<cache eviction="FIFO" flushInterval="10000" size="512" readOnly="false" />-->
<!--//查询全部的方法-->
<select id="getAll" resultType="student" useCache="true" >
select * from student
</select>
<!--//添加的方法-->
<insert id="insertStudent" parameterType="student">
INSERT INTO student(userName,userPwd)VALUES(#{userName},#{userPwd})
</insert>
</mapper>
在StudentTest测试类进行测试
@Test
public void test02() throws Exception{
SqlSession sqlSession = MybatisUtil.creatSqlSession();
//准备user对象
Student student=new Student();
student.setStudentName("zhao");
student.setGradeId(1);
//调用增加的方法
int count = sqlSession.getMapper(StudentMapper.class).insertStudent(student);
//判断结果
if(count>0){
System.out.println("添加成功");
sqlSession.commit();//提交
}else{
System.out.println("添加失败");
sqlSession.rollback();//回滚
}
}
实现结果
修改的方法
在StudentMapper 接口创建查询全部的方法
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
//查询全部
List<Student> getAll();
//添加学生的方法
int insertStudent(Student student);
//修改的方法
int updatePasswordByName( Student student);
}
在StudentMapper.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="com.bdqn.dao.StudentMapper">
<!--<cache eviction="FIFO" flushInterval="10000" size="512" readOnly="false" />-->
<!--//查询全部的方法-->
<select id="getAll" resultType="student" useCache="true" >
select * from student
</select>
<!--//添加的方法-->
<insert id="insertStudent" parameterType="student">
INSERT INTO student(gradeId,studentName)VALUES(#{gradeId},#{studentName})
</insert>
<!--修改的方法-->
<update id="updatePasswordByName" parameterType="student" >
UPDATE student SET userPwd=#{newPwd} WHERE userName=#{userName}
</update>
</mapper>
在StudentTest测试类进行测试
@Test
public void test03() throws Exception{
SqlSession sqlSession = MybatisUtil.creatSqlSession();
//准备user对象
Student student=new Student();
student.setStudentName("ww");
student.setGradeId(3);
//调用修改的方法ff
int count = sqlSession.getMapper(StudentMapper.class).updatePasswordByName(student);
//判断结果
if(count>0){
System.out.println("修改成功");
sqlSession.commit();//提交
}else{
System.out.println("修改失败");
sqlSession.rollback();//回滚
}
}
实现结果
删除的方法
在StudentMapper 接口创建查询全部的方法
package com.bdqn.dao;
import com.bdqn.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
//查询全部
List<Student> getAll();
//添加学生的方法
int insertStudent(Student student);
//修改的方法
int updatePasswordByName( Student student);
//删除的方法
int deleteStudentById(int id);
}
在StudentMapper.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="com.bdqn.dao.StudentMapper">
<!--<cache eviction="FIFO" flushInterval="10000" size="512" readOnly="false" />-->
<!--//查询全部的方法-->
<select id="getAll" resultType="student" useCache="true" >
select * from student
</select>
<!--//添加的方法-->
<insert id="insertStudent" parameterType="student">
INSERT INTO student(gradeId,studentName)VALUES(#{gradeId},#{studentName})
</insert>
<!--修改的方法-->
<update id="updatePasswordByName" parameterType="student" >
UPDATE student SET gradeId=#{gradeId} WHERE studentName=#{studentName}
</update>
<delete id="deleteStudentById" parameterType="int">
delete from student where gradeId=#{gradeId}
</delete>
</mapper>
在StudentTest测试类进行测试
@Test
public void test04() throws Exception{
SqlSession sqlSession = MybatisUtil.creatSqlSession();
//调用修改的方法
int count = sqlSession.getMapper(StudentMapper.class).deleteStudentById(3);
//判断结果
if(count>0){
System.out.println("删除成功");
sqlSession.commit();//提交
}else{
System.out.println("删除失败");
sqlSession.rollback();//回滚
}
}
实现结果