域名备案通过后怎么做网站/nba最新排行
概述
MyBatis的前身的iBatis,是一个支持普通SQL查询、存储过程以及高级映射的持久层框架。其性能优异,具有高度的灵活性、可优化性和易于维护等特点。
MyBatis框架也被称之为ORM(对象关系映射)框架。ORM为一种为了解决面向对象与关系型数据库中数据类型不匹配的技术,通过描述java对象与数据库表之间的映射关系,自动将java应用程序中的对象持久化到关系型数据库的表中。
Hibernate 和 MyBatis的对比
- Hibernate:是一个全表映射的框架,可以根据指定的存储逻辑,自动的生成对应的SQL,并调用JDBC接口来执行,(只需提供POJO和映射关系)因此其开发效率高于MyBatis。但是在多表关联时,对sql查询支持较差;更新数据时,需要发送所有字段;不支持存储过程*;不能通过优化sql来优化性能。因此其执行效率低。
- MyBatis:是一个半自动映射的框架。即相对于全表映射,MyBatis需要手动匹配提供POJO、SQL和映射关系。与Hibernate相比,虽然使用MyBatis手动编写sql要比使用Hibernate工作量大,但是MyBatis可以配置动态SQL并优化SQL,可通过配置决定SQL的映射规则,它还支持存储过程。
MyBatis入门程序的查询功能
步骤:
- 读取配置文件;
- 根据配置文件构建SQLSessionFactory;
- 通过SQLSessionFactory创建SQLSession;
- 使用SqlSession对象操作数据库(查询、添加、修改、删除以及提交事务等);
- 关闭SqlSession。
案例演示:
导包(导入MyBatis的核心包和依赖包以及mysql的驱动包)
创建数据库表t_customer
创建log4j.properties文件(用于输出日志信息)
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# 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
在po包下创建一个Customer.java,属性和数据库表字段相对应。
package po;public class Customer {private Integer id;private String username;private String jobs;private String phone;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getJobs() {return jobs;}public void setJobs(String jobs) {this.jobs = jobs;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Overridepublic String toString() {return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";}}
在mapper包下创建映射文件CustomerMapper.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="mapper.CustomerMapper"><!-- mapper以下的常用标签有sql、insert、delete、update、resultMap --><!--根据客户编号获取客户信息 --><!--#{id} 为占位符,id则表示该占位符等待接收参数的名称为idparameterType指定占位符中的参数类型为Integer;resultType为手动映射,若bean属性和表字段一致,则可以直接自动映射。--><select id="findCustomerById" parameterType="Integer"resultType="po.Customer">select * from t_customer where id = #{id}</select><!--根据客户名模糊查询客户信息列表--><select id="findCustomerByName" parameterType="String"resultType="po.Customer"><!--以下两种写法均正确1. #{} 相当于占位符?==‘j’2.当用${}时,{}内只能是value,而#{}的{}内可以是任意的。3.“%”,'j',“%” 相当于是 '%',#{value},'%',因此'%${value}%'可以表示成 '%',#{value},'%'此外,${}是sql字符串拼接,无法防止sql注入问题,可以使用concat()函数进行字符串拼接。--><!-- select * from t_customer where username like '%${value}%' -->select * from t_customer where username like concat('%',#{value},'%')</select></mapper>
创建MyBatis的核心配置文件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">
<configuration><!--1.配置环境 ,默认的环境id为mysql--><!-- 当MyBatis和spring整合后,environment配置将被废除 --><environments default="mysql"><!--1.2.配置id为mysql的数据库环境 --><environment id="mysql"><!-- 使用JDBC的事务管理 --><transactionManager type="JDBC" /><!--数据库连接池 --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="123456" /></dataSource></environment></environments><!--2.配置Mapper的位置 --><!-- 标签mappers下可以有多个mapper --><mappers><mapper resource="com/test_four/mapper/StudentMapper.xml" /><mapper resource="mapper/CustomerMapper.xml" /></mappers></configuration>
在test包下创建MyBatisTest.java
根据用户编号查询部分
@Testpublic void findCustomerByIdTest() throws Exception {// 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行映射文件中定义的SQL,并返回映射结果Customer customer = sqlSession.selectOne("mapper"+ ".CustomerMapper.findCustomerById", 1);// 打印输出结果System.out.println(customer.toString());// 5、关闭SqlSessionsqlSession.close();}
运行结果:
根据用户名模糊查询部分
@Testpublic void findCustomerByNameTest() throws Exception{ // 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行映射文件中定义的SQL,并返回映射结果List<Customer> customers = sqlSession.selectList("mapper"+ ".CustomerMapper.findCustomerByName", "j");for (Customer customer : customers) {//打印输出结果集System.out.println(customer);}// 5、关闭SqlSessionsqlSession.close();}
运行结果
其中根据客户编号精确查询客户信息的返回类型是Customer,调用方法是selectOne,返回的是一个用户
根据用户名模糊查询的返回类型的泛型,调用的方法是selectList
MyBatis入门程序的添加信息
customerMapper.xml中添加如下映射
<!-- 添加客户信息 --><!-- 这里的#{username}不需要customer.username因为只要{}里的值和bean属性一致,就可以将其属性值传入到SQL语句中 --><insert id="addCustomer" parameterType="po.Customer">insert into t_customer(username,jobs,phone)values(#{username},#{jobs},#{phone})</insert>
MyTest.java中添加测试代码
@Testpublic void addCustomerTest() throws Exception{ // 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行添加操作// 4.1创建Customer对象,并向对象中添加数据Customer customer = new Customer();customer.setUsername("rose");customer.setJobs("student");customer.setPhone("13333533092");// 4.2执行SqlSession的插入方法,返回的是SQL语句影响的行数int rows = sqlSession.insert("mapper"+ ".CustomerMapper.addCustomer", customer);// 4.3通过返回结果判断插入操作是否执行成功if(rows > 0){System.out.println("您成功插入了"+rows+"条数据!");}else{System.out.println("执行插入操作失败!!!");}// 4.4提交事务,若无提交事务,则无法将信息写入数据库表中sqlSession.commit();// 5、关闭SqlSessionsqlSession.close();}
运行截图
插入数据后的表
改进插入数据后返回id
mapper文件修改如下
<insert id="addCustomer" parameterType="po.Customer"><selectKey keyProperty="id" resultType="Integer" order="AFTER"><!-- 查找最后插入的id -->select LAST_INSERT_ID()</selectKey>insert into t_customer(username,jobs,phone)values(#{username},#{jobs},#{phone})</insert>
测试代码修改如下
@Testpublic void addCustomerTest() throws Exception{ // 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行添加操作// 4.1创建Customer对象,并向对象中添加数据Customer customer = new Customer();customer.setUsername("anny");customer.setJobs("student");customer.setPhone("13333533092");// 4.2执行SqlSession的插入方法,返回的是SQL语句影响的行数int rows = sqlSession.insert("mapper"+ ".CustomerMapper.addCustomer", customer);// 4.3通过返回结果判断插入操作是否执行成功if(rows > 0){System.out.println("您成功插入了"+rows+"条数据!");}else{System.out.println("执行插入操作失败!!!");}// 4.4提交事务,若无提交事务,则无法将信息写入数据库表中sqlSession.commit();System.out.println(customer.getId());// 5、关闭SqlSessionsqlSession.close();}
运行结果如图
数据库表如下
更新用户
<!-- 更新客户信息 --><update id="updateCustomer" parameterType="po.Customer">update t_customer setusername=#{username},jobs=#{jobs},phone=#{phone}where id=#{id}</update>
测试
@Testpublic void updateCustomerTest() throws Exception{ // 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行更新操作// 4.1创建Customer对象,对对象中的数据进行模拟更新Customer customer = new Customer();customer.setId(4);customer.setUsername("rose");customer.setJobs("programmer");customer.setPhone("13311111111");// 4.2执行SqlSession的更新方法,返回的是SQL语句影响的行数int rows = sqlSession.update("mapper"+ ".CustomerMapper.updateCustomer", customer);// 4.3通过返回结果判断更新操作是否执行成功if(rows > 0){System.out.println("您成功修改了"+rows+"条数据!");}else{System.out.println("执行修改操作失败!!!");}// 4.4提交事务sqlSession.commit();// 5、关闭SqlSessionsqlSession.close();}
运行截图
删除用户
!-- 删除客户信息 --><delete id="deleteCustomer" parameterType="Integer">delete from t_customer where id=#{id}</delete>
@Testpublic void deleteCustomerTest() throws Exception{ // 1、读取配置文件String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 2、根据配置文件构建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 3、通过SqlSessionFactory创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 4、SqlSession执行删除操作// 4.1执行SqlSession的删除方法,返回的是SQL语句影响的行数int rows = sqlSession.delete("mapper"+ ".CustomerMapper.deleteCustomer", 4);// 4.2通过返回结果判断删除操作是否执行成功if(rows > 0){System.out.println("您成功删除了"+rows+"条数据!");}else{System.out.println("执行删除操作失败!!!");}// 4.3提交事务sqlSession.commit();// 5、关闭SqlSessionsqlSession.close();}
运行截图