1.mybatis帮助开发文档
2.如何使用
说如何使用之前说明一下mybatis的优点
Mybatis解决的问题
1、数据库连接的创建、释放连接的频繁操作造成资源的浪费从而影响系统的性能。
2、SQL语句编写在代码中,硬编码造成代码不容易维护,实际应用中SQL语句变化的可能性比较大,一旦变动就需要改变java类。
3、使用preparedStatement的时候传递参数使用占位符,也存在硬编码,因为SQL语句变化,必须修改源码。
4、对结果集的解析中也存在硬编码。
原本的JDBC连接数据库的使用比较繁琐,需要我们人为的创建连接,操作完数据后再关闭连接,代码书写重复非常重复,对数据的结果映射处理起来也相对麻烦。
public class TestJDBC {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT";
//获取连接
conn= DriverManager.getConnection(url,"root","root");
//SQL语句
String sql="select * from team;";
ps=conn.prepareStatement(sql);
//执行查询
rs = ps.executeQuery();
//遍历结果集
List<Team> list=new ArrayList<>();
while (rs.next()){
Team team=new Team();
team.setTeamName(rs.getString("teamName"));
team.setTeamId(rs.getInt("teamId"));
team.setCreateTime(rs.getDate("createTime"));
team.setLocation(rs.getString("location"));
list.add(team);
}
list.forEach(team -> System.out.println(team));
}catch (Exception e){
e.printStackTrace();
}finally {
try {
//关闭资源
if (rs != null){
rs.close();
}
if (ps != null){
ps.close();
}
if (conn != null){
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
mybaits的使用
1.创建一张表
CREATE TABLE `team` ( `teamId` int NOT NULL AUTO_INCREMENT COMMENT '球队ID', `teamName` varchar(50) DEFAULT NULL COMMENT '球队名称', `location` varchar(50) DEFAULT NULL COMMENT '球队位置', `createTime` date DEFAULT NULL COMMENT '球队建立时间', PRIMARY KEY (`teamId`) ) ENGINE=InnoDB AUTO_INCREMENT=1003 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
2.引入依赖
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
3.编写Mybatis的配置文件
一般情况下:配置文件的名称可以自定义,课程中使用mybatis.xml。配置文件放置在java/resources中。
头文件去官网中复制粘贴。在这里给大家提供一个中文的网站。mybatis – MyBatis 3 | 简介<?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> <!--配置 mybatis 环境--> <environments default="development"> <!--id:数据源的名称--> <environment id="development"> <!--事务类型:使用 JDBC 事务,使用 Connection 的提交和回滚--> <transactionManager type="JDBC"></transactionManager> <!--数据源 dataSource:创建数据库 Connection 对象 type: POOLED 使用数据库的连接池 --> <dataSource type="POOLED"> <!--连接数据库的四大参数 注意数据库版本使用的是MySQL8,如果是mysql5的话,driver和url都不一样,参考学过的JDBC--> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis? useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
4.创建与数据库team表对应的实体类
实体类中的属性必须与表中的列名保持一致,不一样情况如何进行处理呢?
package com.kkb.pojo; import java.util.Date; /** * 与数据库表对应的实体类 */ public class Team { private Integer teamId; private String teamName; private String location; private Date createTime; @Override public String toString() { return "Team{" + "teamId=" + teamId + ", teamName='" + teamName + '\'' + ", location='" + location + '\'' + ", createTime=" + createTime + '}'; } //省略set get方法 }
5.编写ORM映射文件
我们是针对实体类Team.java和表Team进行ORM映射.
Mybatis框架中,ORM映射是针对SQL语句进行,Mybatis框架将SQL语句抽取到了XML中。所以我们需要针对每个实体类编写XML映射文件。注意:XML映射文件必须与实体类在同一个包下面,且文件名称一致,类型分别是.java .xml
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">
<!--namespace="名称必须与映射的类的名字一致,是完全限定名"-->
<mapper namespace="com.kkb.pojo.Team">
<!-- id="自定义名称,id不能重复;相当于dao中的方法名称"
resultType="使用的要求:实体类中的属性名与表中的列名一致"
-->
<select id="queryAll" resultType="com/kkb/pojo/Team">
select * from team;
</select>
</mapper>
6. 将映射文件注册到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> <environments default="development"> <environment id="development"> ...... </environment> </environments> <!-- 注册映射文件 --> <mappers> <mapper resource="com/kkb/pojo/Team.xml"/> </mappers> </configuration>
7.pom.xml文件配置映射文件的扫描路径
<build> <resources> <!-- resources文件 --> <resource> <directory>src/main/resources</directory> <!-- 是否被过滤,如果被过滤则无法使用 --> <filtering>false</filtering> </resource> <!-- java文件夹 --> <resource> <directory>src/main/java</directory> <!-- 引入映射文件等 --> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> <plugins> ...... </plugins> </build>
7.使用Mybatis框架的核心接口测试
package com.kkb.test; import com.kkb.pojo.Team; 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.IOException; import java.io.Reader; import java.util.List; public class test { //mybatis的配置文件--相当于创建工厂的图纸 private String resource="mybatis.xml"; @Test public void testFindAll(){ try { //1、读取mybatis的配置文件 Reader reader = Resources.getResourceAsReader(resource) ; //2、创建SqlSessionFactory对象,目的是获取sqlSession--根据图纸创建工厂 SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); //3、创建可以执行SQL语句的SqlSession--工厂创建产品 SqlSession sqlSession = sqlSessionFactory.openSession(); //4、执行SQL语句 List<Team> teamList = sqlSession.selectList("com.kkb.pojo.Team.qureyAll"); //5、循环输出查询的结果 for (Team team : teamList) { System.out.println(team); } //6、关闭SqlSession,释放资源 sqlSession.close(); } catch (IOException e) { e.printStackTrace(); } } }
测试结果:
8.mybatis 的增删改操作
在配置好mybatis的配置文件中的environment 和mapper属性后进行mybaits的增删改操作。
team.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"> <!--namespace="名称必须与映射的类的名字一致,是完全限定名"--> <mapper namespace="com.kkb.pojo.Team"> <!-- id="自定义名称,id不能重复;相当于dao中的方法名称" resultType="使用的要求:实体类中的属性名与表中的列名一致" --> <select id="queryAll" resultType="com.kkb.pojo.Team"> select * from team; </select> <!--根据ID查询 parameterType="参数的类型",目前只支持一个参数可以不写,mybatis会自动推断类型 where teamId=#{id}: #{id}表示参数 id-自定义,只需要符合命名规范即可,没有实际对应意义 --> <select id="queryById" parameterType="int" resultType="com.kkb.pojo.Team"> select * from team where teamId=#{id} </select> <!--添加一个球队 parameterType="com.kkb.pojo.Team" 将对象作为参数, #{值} 值必须是实体类中的属性名称,其实就是占位符? --> <insert id="add" parameterType="com.kkb.pojo.Team" > INSERT INTO `team` (`teamName`, `location`, `createTime`) VALUES (#{teamName}, #{location}, #{createTime}) </insert> <!--更新一个球队--> <select id="update" parameterType="com.kkb.pojo.Team"> update team set teamName=#{teamName},location=#{location} where teamId=#{teamId} </select> <!--删除一个球队 --> <delete id="del" > delete from team where teamId=#{id} </delete> </mapper>
test类
package com.kkb.test; import com.kkb.pojo.Team; 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.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.Reader; import java.util.Date; import java.util.List; public class test { //mybatis的配置文件--相当于创建工厂的图纸 private String resource="mybatis.xml"; private SqlSession sqlSession; @Before public void before() throws IOException { //1、读取mybatis的配置文件 Reader reader = Resources.getResourceAsReader(resource) ; //2、创建SqlSessionFactory对象,目的是获取sqlSession--根据图纸创建工厂 SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); //3、创建可以执行SQL语句的SqlSession--工厂创建产品 sqlSession = sqlSessionFactory.openSession();//这里设置为true的话就不用手动提交了openSession(true) } @After public void after(){ sqlSession.close(); } @Test public void testFindAll() { List<Team> teamList = sqlSession.selectList("com.kkb.pojo.Team.queryAll"); //5、循环输出查询的结果 for (Team team : teamList) { System.out.println(team); } } @Test public void testFindById() { Team team = sqlSession.selectOne("com.kkb.pojo.Team.queryById", 1003); System.out.println(team); } @Test public void testAdd(){ Team team=new Team(); team.setTeamName("wqs的球队"); team.setLocation("北京"); team.setCreateTime(new Date()); int num = sqlSession.insert("com.kkb.pojo.Team.add", team);//增删改必须手动提交事务 sqlSession.commit();//手动提交事务 System.out.println(num); } @Test public void testUpdate(){ Team team=sqlSession.selectOne("com.kkb.pojo.Team.queryById",1049); team.setTeamName("lw的球队"); team.setLocation("洛杉矶"); int num = sqlSession.update("com.kkb.pojo.Team.update", team); sqlSession.commit(); System.out.println(num); } @Test public void del(){ int delete = sqlSession.delete("com.kkb.pojo.Team.del", 1049); if(delete==1){ System.out.println("删除成功"); }else { System.out.println("删除失败"); } } }
配置日志文件
1 添加jar依赖
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2 添加日志配置文件
在resource下添加log4j.properties配置文件
# Global logging configuration info warning error 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
3.在mybatis配置文件中添加日志的配置
<configuration> <!--配置日志,注意顺序:查看属性点击configuration进入查看即可--> <settings> <setting name="logImpl" value="LOG4J" /> </settings> ......
使用mybaits开发的步骤