Mybatis实现简单的数据库增删改查操作
作者:互联网
简介:
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis的功能架构:
分为三层
1.API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
2.数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
3.基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。
优点:
1.解除sql与程序代码的耦合:通过提供DAL层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
2.提供映射标签,支持对象与数据库的orm字段关系映射
3.提供对象关系映射标签,支持对象关系组建维护
4.提供xml标签,支持编写动态sql。
使用Mybatis实现简单的数据库增删改查操作
1、进行数据库的建表:
classinfo表
student表
2、实体类
package cn.yyj.entity;
//实体
public class StudentInfo {
private String studentid;
private String studentName;
private String studentSex;
private String studentPhone;
private String studentAddress;
private int studentAge;
private int stuclassid;
//私有的 类型 名字
private String className;
//get set 方法
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentSex() {
return studentSex;
}
public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}
public String getStudentPhone() {
return studentPhone;
}
public void setStudentPhone(String studentPhone) {
this.studentPhone = studentPhone;
}
public String getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(String studentAddress) {
this.studentAddress = studentAddress;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public int getStuclassid() {
return stuclassid;
}
public void setStuclassid(int stuclassid) {
this.stuclassid = stuclassid;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
//有参
public StudentInfo(String studentid, String studentName, String studentSex, String studentPhone, String studentAddress, int studentAge, int stuclassid, String className) {
this.studentid = studentid;
this.studentName = studentName;
this.studentSex = studentSex;
this.studentPhone = studentPhone;
this.studentAddress = studentAddress;
this.studentAge = studentAge;
this.stuclassid = stuclassid;
this.className = className;
}
public StudentInfo(String studentid, String studentName, String studentSex, String studentPhone, String studentAddress, int studentAge, int stuclassid) {
this.studentid = studentid;
this.studentName = studentName;
this.studentSex = studentSex;
this.studentPhone = studentPhone;
this.studentAddress = studentAddress;
this.studentAge = studentAge;
this.stuclassid = stuclassid;
}
//无参
public StudentInfo() {
}
}
2、mapper接口实现类
ackage cn.yyj.mapper;
//dao层
import cn.yyj.entity.StudentInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface StudentInfoMapper {
//查询所有 查询到很多学生都放进list集合里面 集合里面存放的都是查询出来的学生
public List<StudentInfo> findStudentAll();
//根据ID查询
public StudentInfo findStudentById(String id);
//根据姓来进行模糊查询
public List<StudentInfo> findStudentByName(String name);
//多条件查询
public List<StudentInfo> findStudentByMap(Map<String,Object>map);
//年龄查询
public List<StudentInfo> findStudentByAge(@Param("age") int age);
//修改学生信息
public int update(StudentInfo si);
//删除
public int delete(String id);
//添加
public int insert(StudentInfo si);
}
3、创建相应的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.xml 中的namespace 设置为 mapper.java 的全限定名。 -->
<!-- 该映射文件取代了dao的实现类
namespace是指要实现的接口的全限定名 -->
<mapper namespace="cn.yyj.mapper.StudentInfoMapper">
<!--配置结果的类型 类型是StudentInfo id起个名字 -->
<resultMap id="stulist" type="StudentInfo">
<!--配置结果 property 实体类的属性是什么————对应——column 这个类在数据库表中所对应的字段 (害怕两个类属性不一样) -->
<result property="studentid" column="studentid"></result>
<result property="studentName" column="studentName"></result>
<result property="studentSex" column="studentSex"></result>
<result property="studentPhone" column="studentPhone"></result>
<result property="studentAddress" column="studentAddress"></result>
<result property="studentAge" column="studentAge"></result>
<result property="stuclassid" column="stuclassid"></result>
<result property="className" column="className"></result>
</resultMap>
<!--/* 查询到s.*学生表里所有内容以及c.className 班级表里的班级名称 对应上面结果类型 */-->
<select id="findStudentAll" resultMap="stulist" >
select s.*,c.className from student s,classinfo c where s.stuclassid=c.classid
</select>
<!--/* #{} 参数相当于原来的占位符 方法名findStudentByTd 类型StudentInfo 参数类型String */-->
<select id="findStudentById" resultType="StudentInfo" parameterType="String">
SELECT * FROM student WHERE studentid=#{studentid}
</select>
<!--id=查询的方法 参数类型String 结果类型 findStudentById -->
<!-- 模糊查询 拼接函数concat(concat('%',#{studentName},'%')) -->
<select id="findStudentByName" resultType="StudentInfo" parameterType="String">
SELECT * FROM student where studentName like concat(concat('%',#{studentName},'%'))
</select>
<!--多条件查询 根据姓名和年龄做查询 studentName和map里面的key值是一样的不然找不到-->
<select id="findStudentByMap" resultType="StudentInfo" parameterType="Map">
SELECT * FROM student WHERE studentName like concat(concat('%',#{studentName}),'%')AND studentAge>#{studentAge}
</select>
<select id="findStudentByAge" parameterType="int" resultType="StudentInfo">
SELECT * FROM student WHERE studentAge>#{age}
</select>
<update id="update" parameterType="StudentInfo" >
UPDATE student set studentName=#{studentName},studentSex=#{studentSex},studentPhone=#{studentPhone},studentAddress=#{studentAddress},studentAge=#{studentAge} WHERE studentid=#{studentid}
</update>
<delete id="delete" parameterType="StudentInfo">
DELETE FROM student WHERE studentid=#{studentid}
</delete>
<insert id="insert" parameterType="StudentInfo">
INSERT INTO student VALUES (#{studentid},#{studentName},#{studentSex},#{studentPhone},#{studentAddress},#{studentAge},#{stuclassid})
</insert>
</mapper>
4、mybatis文件配置
<?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>
<typeAliases>
<!--所有类型都在包entity里面 所以在mapper.xml只用写包里面的的内容就行了-->
<package name="cn.yyj.entity"></package>
</typeAliases>
<!-- 设置一个默认的连接环境信息 -->
<environments default="aa">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="aa">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="JDBC"></transactionManager>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="POOLED">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/school2"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</dataSource>
</environment>
</environments>
<!--配置接口所对应的xml文件-->
<!-- 加载映射文件-->
<mappers>
<mapper resource="cn/yyj/mapper/StudentInfoMapper.xml"></mapper>
</mappers>
</configuration>
5、工具类
package cn.yyj.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtil {
//加载mybatis配置文件
//创建sqlsessionfactory对象
//创建sqlsession连接对象
//创建关闭sqlsession连接对象
//mybatis 数据库查询
private static SqlSessionFactory sessionFactory;
static{
String resource="mybatis1.xml";
try {
InputStream is=Resources.getResourceAsStream(resource);
sessionFactory=new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sessionFactory.openSession();
}
public static void closeSession(SqlSession session){
if(session!=null){
session.close();
}
}
}
6、测试类
package cn.yyj.test;
import cn.yyj.entity.StudentInfo;
import cn.yyj.mapper.StudentInfoMapper;
import cn.yyj.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.test.context.jdbc.Sql;
import java.util.HashMap;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
// test1();
// test2();
// test3();
// test4();
// test5();
test6();
// test7();
// test8();
}
private static void test8() {
SqlSession session=MybatisUtil.getSession();
int a=session.getMapper(StudentInfoMapper.class).insert(new StudentInfo("s332256","老博文","男","2313553135","河南驻马店",20,1));
if (a>0){
System.out.println("yes");
}
session.commit();
}
private static void test7() {
SqlSession session=MybatisUtil.getSession();
StudentInfo lists=session.getMapper(StudentInfoMapper.class).findStudentById("s332255");
if (lists!=null){
int a= session.getMapper(StudentInfoMapper.class).delete(lists.getStudentid());
if (a>0){
System.out.println("OK");
}
}
session.commit();
}
private static void test6() {
SqlSession session=MybatisUtil.getSession();
StudentInfo lists=session.getMapper(StudentInfoMapper.class).findStudentById("s332255");
lists.setStudentAge(40);
lists.setStudentSex("女");
int a=session.getMapper(StudentInfoMapper.class).update(lists);
if (a>0){
System.out.println("ok");
}
session.commit();
}
private static void test5() {
SqlSession session=MybatisUtil.getSession();
List<StudentInfo> lists=session.getMapper(StudentInfoMapper.class).findStudentByAge(22);
for (StudentInfo u:lists){
System.out.println(u.getStudentName());
}
}
private static void test4() {
SqlSession session=MybatisUtil.getSession();
HashMap<String, Object> map = new HashMap<String, Object>();
//通过map.put去存值
map.put("studentName","赵");
map.put("studentAge",10);
List<StudentInfo> lists=session.getMapper(StudentInfoMapper.class).findStudentByMap(map);
for (StudentInfo u:lists){
System.out.println(u.getStudentName());
}
}
private static void test3() {
SqlSession session = MybatisUtil.getSession();
//用集合接收 姓张的 查询到的是一个集合
List<StudentInfo> lists=session.getMapper(StudentInfoMapper.class).findStudentByName("张");
for (StudentInfo u:lists){
System.out.println(u.getStudentName());
}
}
private static void test2() {
SqlSession session = MybatisUtil.getSession();
//根据ID查询 只能查到一个 不是一个集合 将其用lists接收
StudentInfo lists=session.getMapper(StudentInfoMapper.class).findStudentById("s123452");
//获取其StudentName 并输入
System.out.println(lists.getStudentName());
}
private static void test1() {
SqlSession session = MybatisUtil.getSession();
//调用Mapper这个方法 用集合接收
List<StudentInfo> lists=session.getMapper(StudentInfoMapper.class).findStudentAll();
//循环遍历 输出
for (StudentInfo u:lists){
System.out.println(u.getStudentName()+"\t"+u.getClassName());
}
}
}
结果展示:
test1:
test2:
test3:
test4:
test5:
test6:
test7:
test8:
标签:studentName,String,studentid,void,改查,增删,session,Mybatis,public 来源: https://blog.csdn.net/yangyingjian123/article/details/114713299