Java开发在以前做数据库连接的时候通过JDBC来完成,非常麻烦。
现在引入了MyBatis这个框架,Mybatis是简化数据库操作的持久层框架。
使用Mybatis的好处:
- mybatis 可以将对数据表的操作(sql,方法)等等直接剥离,写到 xml 配置文件,实现和 java 代码的解耦
- MyBatis 在 java 和 sql 之间提供更灵活的映射
1、java以Mybatis方式操作DB
1.1、配置数据源-创建 resources/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置mybatis自带的日志输出--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!-- 配置类型别名--> <typeAliases> <typeAlias type="com.linghu.entity.Monster" alias="Monster"/> </typeAliases> <environments default="development"> <environment id="development"> <!-- 配置事务管理器--> <transactionManager type="JDBC"/> <!-- 配置数据源--> <dataSource type="POOLED"> <!-- 配置驱动--> <property name="driver" value="com.mysql.jdbc.Driver"/> <!-- 配置数据库的链接--> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <!-- 数据库的用户名和密码--> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 这里设置我们需要管理的mapper.xml文件--> <!-- 可以通过快捷键copy这个地址--> <mappers> <mapper resource="com/linghu/mapper/MonsterMapper.xml"/> </mappers> </configuration>
1.2、创建java bean-Monster
创建bean的时候要对照自己设计的数据库表字段进行设计,要一一对应!
package com.linghu.entity; import java.util.Date; /** * @author 令狐荣豪 * @version 1.0 * Monster类和monster表有对应关系,字段要对应 * 体现oop */ public class Monster { private Integer id; private Integer age; private String name; private String email; private Date birthday; private double salary; private Integer gender; public Monster() { } public Monster(Integer id, Integer age, String name, String email, Date birthday, double salary, Integer gender) { this.id = id; this.age = age; this.name = name; this.email = email; this.birthday = birthday; this.salary = salary; this.gender = gender; } @Override public String toString() { return "Monster{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + ", email='" + email + '\'' + ", birthday=" + birthday + ", salary=" + salary + ", gender=" + gender + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } }
1.3、配置Mapper接口声明方法
package com.linghu.mapper; import com.linghu.entity.Monster; import java.util.List; /** * @author 令狐荣豪 * @version 1.0 * 定义增删改查的接口方法 */ public interface MonsterMapper { // 添加monster public void addMonster(Monster monster); //根据id删除一个Monster public void delMonster(Integer id); //修改 Monster public void updateMonster(Monster monster); //查询-根据 id public Monster getMonsterById(Integer id); //查询所有的 Monster public List<Monster> findAllMonster(); }
1.4、配置xxMapper,完成SQL配置,实现CRUD操作
Monstermapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.linghu.mapper.MonsterMapper"> <!-- <select id="selectBlog" resultType="Blog">--> <!-- select * from Blog where id = #{id}--> <!-- </select>--> <!-- private Integer id; private Integer age; private String name; private String email; private Date birthday; private double salary; private Integer gender;--> <insert id="addMonster" parameterType="com.linghu.entity.Monster"> insert into `monster` (`age`,`birthday`,`email`,`gender`,`name`,`salary`) <!-- values(10,null,'linghu@qq.com',1,'kate',1000),修改成活数据--> <!-- 下面的名称对应的Monster对象的属性名--> values(#{age},#{birthday},#{email},#{gender},#{name},#{salary}) </insert> <delete id="delMonster" parameterType="Integer"> delete from `monster` where id=#{id}; </delete> <!-- 这里的入参类型最好不要简写!--> <!-- 配置类型别名后这里可以简写Monster--> <!-- <update id="updateMonster" parameterType="com.linghu.entity.Monster">--> <update id="updateMonster" parameterType="Monster"> update `monster` set `age`=#{age},`birthday`=#{birthday},`email`=#{email}, `gender`=#{gender},`name`=#{name},`salary`=#{salary} where id=#{id} </update> <!-- resultType是个别名--> <select id="getMonsterById" parameterType="Integer" resultType="Monster"> select * from `monster` where id=#{id}; </select> <!-- 查询全部结果--> <select id="findAllMonster" resultType="Monster"> select * from `monster`; </select> </mapper>
1.5、Test测试
package com.linghu.mapper; import com.linghu.entity.Monster; import com.linghu.util.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Before; import org.junit.Test; import java.util.Date; import java.util.List; /** * @author 令狐荣豪 * @version 1.0 */ public class MonsterMapperTest { private SqlSession sqlSession; private MonsterMapper monsterMapper; @Before public void init(){ //通过SqlSessionFactory获取一个SqlSession会话 sqlSession= MyBatisUtils.getSqlSession(); //获取MonsterMapper接口对象,该对象实现了MonsterMapper monsterMapper=sqlSession.getMapper(MonsterMapper.class); System.out.println(monsterMapper.getClass()); } // @Test // public void t1(){ // System.out.println("t1()。。。"); // } @Test public void addMonster(){ for (int i=0;i<3;i++){ Monster monster = new Monster(); monster.setAge(10+i); monster.setBirthday(new Date()); monster.setEmail("lignhu@qq.com"); monster.setGender(1); monster.setName("松鼠精"+i); monster.setSalary(1000+i*10); // id不用设置 monsterMapper.addMonster(monster); System.out.println("添加对象-"+monster); } //如果是增删改,需要提交事务 if (sqlSession!=null){ sqlSession.commit(); sqlSession.close(); } System.out.println("保存成功···"); } @Test public void delMonster(){ monsterMapper.delMonster(2); //如果是增删改,需要提交事务 if (sqlSession!=null){ sqlSession.commit(); sqlSession.close(); } System.out.println("删除成功···"); } @Test public void updateMonster(){ Monster monster = new Monster(); monster.setAge(200); monster.setBirthday(new Date()); monster.setEmail("hspedu@sohu.com"); monster.setGender(2); monster.setName("狐狸精"); monster.setSalary(9234.89); monster.setId(4); monsterMapper.updateMonster(monster); if (sqlSession != null) { sqlSession.commit(); sqlSession.close(); } System.out.println("修改 ok"); } @Test public void getMonsterById(){ // Monster monster = new Monster(); Monster monster=monsterMapper.getMonsterById(6); System.out.println("monster="+monster); if (sqlSession != null) { sqlSession.commit(); sqlSession.close(); } System.out.println("查询 ok"); } @Test public void findAllMonster(){ //查询全部结果 List<Monster> allMonster = monsterMapper.findAllMonster(); for (Monster monster :allMonster) { System.out.println(monster); } if (sqlSession != null) { sqlSession.close(); } System.out.println("查询 ok"); } }
2、需要的Utils工具类
工具类:MyBatisUtils.java
package com.linghu.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 javax.annotation.Resource; import java.io.IOException; import java.io.InputStream; /** * @author 令狐荣豪 * @version 1.0 * 这是一个工具类,可以得到Sqlsession会话,这个会话提供了执行SQL命令的方法CRUD */ public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static {//静态代码块-初始化sqlSessionFactory对象 try { /** * 指定资源文件 */ String resource="mybatis-config.xml"; //指定资源文件流 InputStream inputStream = Resources.getResourceAsStream(resource); //获取SqlSession实例 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } /** * 返回一个SQLSession会话,这个会话提供了执行SQL命令的方法CRUD * @return */ public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
3、pom基础依赖
<?xml version="1.0" encoding="UTF-8"?> <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.linghu</groupId> <artifactId>Linghu_Mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <!-- 这里可以看到父项目下有哪些子项目--> <module>mybatisqucikstart</module> </modules> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- 导入依赖 --> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <!-- 配置resources--> <!-- 配置目的:将src/main/java目录和子目录和src/main/resources目录和子目录的 资源文件xml和properties在build项目时,导出到对应的target目录下 --> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> </build> </project>
4、数据库建表操作
CREATE DATABASE `mybatis` CREATE TABLE `monster` ( `id` INT NOT NULL AUTO_INCREMENT, `age` INT NOT NULL, `birthday` DATE DEFAULT NULL, `email` VARCHAR(255) NOT NULL , `gender` TINYINT NOT NULL, `name` VARCHAR(255) NOT NULL, `salary` DOUBLE NOT NULL, PRIMARY KEY (`id`) ) CHARSET=utf8