标签:pil .sql 利用 rac setter ola block you arc
mybatis是一个持久层框架,主要作用就是在java中操作数据库,其实就是在jdbc的基础上进行的封装。使用mybatis之后,开发者不用再花费精力去处理诸如注册驱动、创建Connection、配置Statement等繁琐过程。与之前学习的spring mvc要运行在web容器不同,mybatis不需要web容器,在c/s架构和b/s架构下均可运行。早期叫做iBatis,后来改名为myBati
利用 mybatis 将i个Student对象中的数据存储到数据库中
1:创建一个maven项目,在pom.xml文件中引入相关jar包
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies># 为了调试方便,会使用到 junit ,在创建maven项目时已自动加入 junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>compile</scope> </dependency>2:在pom.xml配置文件中的 build 标签中添加如下数据
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <!-- 因为在后面的步骤中,会在dao包下创建xml文件,如果未加入上面的内容,
maven是不会将xml文件发布到编译后的classes目录下,这样就导致mybatis找不到该配置文件 -->3:创建一个Student实体类
package com.doaoao.bean; public class Student { private int id; private String name; private int age; private double score; public Student(String name, int age, double score) { this.name = name; this.age = age; this.score = score; } // 省略所创建的getter和setter }4:创建数据库,并创建数据库表
-- 建表语句 CREATE TABLE `learnmybatis`.`t_student` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(20) NULL, `age` INT NULL, `score` DOUBLE NULL, PRIMARY KEY (`id`));5:创建接口 StudentDao
package com.doaoao.dao; import com.doaoao.bean.Student; public interface StudentDao { void insertStudent(Student student); }6:添加映射文件
主要在里面编写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="doaoao"> <!--parameterType可省略--> <insert id="insertStudent" parameterType="com.doaoao.bean.Student"> INSERT INTO t_student(name,age,score) VALUES (#{name},#{age},#{score}) </insert> </mapper> <!-- 注 --> <!-- mybatis会检测到student对象,所以上方的属性paramterType一般不用指定 --> <!-- Value前面的 name age score指的是数据库中的属性名,Value后面的name age score指的是类Student中的属性名 -->7:添加mybatis的配置文件 mybatis.xml (可随意命名,放于resources目录下)
<?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"> <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/learnmybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--注册映射文件--> <mapper resource="com/doaoao/dao/StudentMapper.xml"/> </mappers> </configuration>8:可添加日志
在resources目录下创建 log4j.properties文件
# 输出全部的操作日志(二选一) log4j.rootLogger=trace,console
# 输出 namespac="doaoao"下的sql语句(在前面第六步添加映射文件时配置的)(二选一)
log4j.logger.doaoao=debug,console#控制台附加器 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern= [%-5p][%d{yyyy-MM-dd HH:mm:ss}]%m%n9:创建接口类的实现,实现接口StudentDao
package com.doaoao.dao.impl; import com.doaoao.bean.Student; import com.doaoao.dao.StudentDao; 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.IOException; import java.io.InputStream; public class StudentDaoImpl implements StudentDao { private SqlSession sqlSession; @Override public void insertStudent(Student student) { try { //读取主配置文件 InputStream input = Resources.getResourceAsStream("mybatis.xml"); //创建SqlSessionFactory对象 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(input); //创建SqlSession对象 sqlSession = sessionFactory.openSession(); //新增数据操作 sqlSession.insert("insertStudent", student); //提交SqlSession sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } }10:创建测试类,使用 junit 运行该测试类(执行时选中类名,右键Run...)
package com.doaoao.test; import com.doaoao.bean.Student; import com.doaoao.dao.StudentDao; import com.doaoao.dao.impl.StudentDaoImpl; import org.junit.Test; public class StudentTest01 { @Test public void insertStudent(){ StudentDao studentDao = new StudentDaoImpl(); Student student = new Student("张三",18,80); studentDao.insertStudent(student); } }
...
重构第一部分:在StudentDaoImpl类中,获取SqlSession对象的操作比较复杂,可以将其封装成一个方法
1:创建一个工具包,并创建一个工具类 MyBatiesUtil.java
package com.doaoao.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 java.io.IOException; import java.io.InputStream; public class MyBatisUtil { public static volatile SqlSessionFactory sqlSessionFactory; public static SqlSession getSqlSession(){ try{ if(sqlSessionFactory == null){ // 读取配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis.xml"); synchronized (MyBatisUtil.class){ if(sqlSessionFactory == null){ sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } } } } catch (IOException e) { e.printStackTrace(); } return sqlSessionFactory.openSession(); } }2:修改类StudentDaoImpl中的内容
package com.doaoao.dao.impl; import com.doaoao.bean.Student; import com.doaoao.dao.StudentDao; import com.doaoao.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; public class StudentDaoImpl implements StudentDao { private SqlSession sqlSession; @Override public void insertStudent(Student student) { // 写在 try括号中让其自动关闭 // SqlSession继承了AutoCloseable接口,可以自动关闭 try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){ sqlSession.insert("insertStudent",student); // 新增数据操作 sqlSession.commit(); // 提交Session } } }
重构第二部分:为了便于管理,会将数据库的一些配置信息放到配置文件中,mybatis.xml配置文件会从该配置文件读取信息
1:在resources目录下创建db.properties配置文件,配置文件内容如下
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/learnmybatis?useSSL=false jdbc.user=root jdbc.password=123456
2:将所创建的数据库配置文件注册到mybatis.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> <!-- 注册配置文件 --> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!--注册映射文件--> <mapper resource="com/doaoao/dao/StudentMapper.xml"/> </mappers> </configuration>
...
...
标签:pil .sql 利用 rac setter ola block you arc
原文地址:https://www.cnblogs.com/Doaoao/p/10701455.html