北京网站制作公司招聘,门户网站建设推广,网站建设做什么会计科目,网站内容建设需要哪些策略呢目录 MyBatis第一章#xff1a;代理Dao方式的CRUD操作1. 代理Dao方式的增删改查 第二章#xff1a;MyBatis参数详解1. parameterType2. resultType 第三章#xff1a;SqlMapConfig.xml配置文件1. 定义properties标签的方式管理数据库的信息2. 类型别名定义 MyBatis
第一章代理Dao方式的CRUD操作1. 代理Dao方式的增删改查 第二章MyBatis参数详解1. parameterType2. resultType 第三章SqlMapConfig.xml配置文件1. 定义properties标签的方式管理数据库的信息2. 类型别名定义 MyBatis
第一章代理Dao方式的CRUD操作
1. 代理Dao方式的增删改查 创建项目 UserMapper接口代码 findAll 方法用于获取所有用户的信息将以 ListUser 形式返回。 findById 是根据用户的唯一标识userId查找用户信息返回单个 User 对象。insert 方法接收一个 User 对象作为参数将其存储到数据库中。 update 方法用于更新用户信息接收一个 User 对象通过对象的属性值更新数据库中对应记录。 delete 方法依据用户 ID 删除相应记录接收一个 Integer 类型的用户 ID。findByName 可根据用户名进行查找以字符串形式接收用户名结果以 ListUser 形式返回适用于模糊查询或精确查询。 findByCount 方法计算用户的总数结果以 Integer 类型返回。 package cn.tx.mapper;import java.util.List;import cn.tx.domain.User;public interface UserMapper {public ListUser findAll();public User findById(Integer userId);public void insert(User user);public void update(User user);public void delete(Integer userId);public ListUser findByName(String username);public Integer findByCount();}UserMapper.xml的配置文件代码 元素的 namespace 属性绑定到对应的 UserMapper 接口确保 XML 中的操作与接口方法关联。 元素中的 findAll 操作使用 select * from user 语句查询所有用户结果将映射为 com.qcbyjy.domain.User 类型的对象。 findById 的 select 操作通过 #{id} 占位符接收 findById 方法传入的用户 ID查询结果映射为 com.qcbyjy.domain.User 类型参数为 int 类型。 insert 操作除了插入数据的 SQL 语句外使用 元素在插入操作后执行通过 select last_insert_id() 获取新插入记录的主键值keyProperty 指明将主键值存储在 User 对象的 id 属性中order“AFTER” 表示在插入之后执行resultType 为 Integer。 update 操作使用 #{} 占位符接收 update 方法传入的 User 对象的属性更新用户表中相应记录。 delete 操作使用 #{id} 接收 delete 方法传入的用户 ID删除相应记录。 findByName 操作的 select 语句使用 like ‘%${value}%’ 进行模糊查询其中 ${value} 接收 findByName 方法传入的用户名存在 SQL 注入风险不推荐使用。 findByCount 操作通过 select count(*) from user 统计用户表中的记录数结果为 int 类型。 ?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.qcbyjy.mapper.UserMapperselect idfindAll resultTypecom.qcbyjy.domain.Userselect * from user/select!-- 通过id查询 SQL语句使用#{占位符的名称名称可以任意}仅限于基本数据类型和String类型--select idfindById resultTypecom.qcbyjy.domain.User parameterTypeintselect * from user where id #{id};/select!--保存操作--insert idinsert parameterTypecom.qcbyjy.domain.User/*keyProperty表示要返回的属性名称order取值AFTER表示插入数据后的行为resultType表示返回值的类型*/selectKey keyPropertyid orderAFTER resultTypejava.lang.Integerselect last_insert_id();/selectKeyinsert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})/insert!-- 修改 --update idupdate parameterTypecom.qcbyjy.domain.Userupdate user set username #{username},birthday #{birthday},sex #{sex},address#{address} where id #{id}/update!-- 删除 --delete iddelete parameterTypeIntegerdelete from user where id #{id}/delete!-- 模糊查询 --select idfindByName resultTypecom.qcbyjy.domain.User parameterTypestring!-- 第一种方式的SQL语句 select * from user where username like #{username}--!-- 第二章SQL语句的编写 强调%${value}%不能修改固定写法不推荐使用 --select * from user where username like %${value}%/select!-- 具体函数的查询 --select idfindByCount resultTypeintselect count(*) from user/select/mapperUserTest的代码 在 init 方法中首先使用 Resources.getResourceAsStream(SqlMapConfig.xml) 从类路径加载配置文件然后使用 SqlSessionFactoryBuilder 创建 SqlSessionFactory进而创建 SqlSession最终通过 session.getMapper(UserMapper.class) 获取 UserMapper 的代理对象。在 Before 注解的 init 方法中进行资源的初始化在 After 注解的 destory 方法中关闭输入流和 SqlSession确保资源的正确管理。testFindAll 测试方法调用 mapper.findAll() 方法查询所有用户将结果存储在 ListUser 中并遍历打印。testFindById 测试方法调用 mapper.findById(41) 查找 ID 为 41 的用户并打印。testInsert 测试方法创建一个新的 User 对象设置属性调用 mapper.insert(user) 插入用户使用 session.commit() 提交事务并打印新插入用户的 id。testUpdate 测试方法先查找用户修改用户信息调用 mapper.update(user) 更新用户信息再提交事务。testDelete 测试方法调用 mapper.delete(48) 删除 ID 为 48 的用户提交事务。testFindByName 测试方法有两种方式第一种传入 %王% 进行模糊查询第二种只传入 王根据配置自动添加通配符进行模糊查询都将结果存储在 ListUser 中并遍历打印。testFindByCount 测试方法调用 mapper.findByCount() 获取用户数量并打印。 package cn.tx.test;import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;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 cn.tx.domain.User;
import cn.tx.mapper.UserMapper;public class UserTest {private InputStream in;private SqlSession session;private UserMapper mapper;Beforepublic void init() throws Exception {// 加载配置文件in Resources.getResourceAsStream(SqlMapConfig.xml);// 创建工厂对象SqlSessionFactory factory new SqlSessionFactoryBuilder().build(in);// 创建Session对象session factory.openSession();// 获取到代理对象mapper session.getMapper(UserMapper.class);}Afterpublic void destory() throws IOException {in.close();session.close();}/*** 测试查询所有的方法* throws Exception */Testpublic void testFindAll() throws Exception {ListUser list mapper.findAll();// 遍历for (User user : list) {System.out.println(user);}in.close();}Testpublic void testFindById() throws Exception {User user mapper.findById(41);System.out.println(user);in.close();}Testpublic void testInsert() throws Exception {User user new User();user.setUsername(美美);user.setBirthday(new Date());user.setSex(男);user.setAddress(顺义);mapper.insert(user);session.commit();System.out.println(user.getId());}Testpublic void testUpdate() throws Exception {User user mapper.findById(41);user.setUsername(小凤);mapper.update(user);session.commit();}Testpublic void testDelete() throws Exception {mapper.delete(48);session.commit();}// 第一种Testpublic void testFindByName() throws Exception {ListUser list mapper.findByName(%王%);for (User user : list) {System.out.println(user);}}// 第二种Testpublic void testFindByName() throws Exception {ListUser list mapper.findByName(王);for (User user : list) {System.out.println(user);}}Testpublic void testFindByCount() throws Exception {Integer count mapper.findByCount();System.out.println(总记录数count);}}模糊查询符号使用的区别 通过#{}可以实现preparedStatement向占位符中设置值自动进行java类型和jdbc类型转换#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值#{}括号中可以是value或其它名称。通过$可以将传入的内容拼接在中且不进行类型转换${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换 ${}可以接收简单类型值或pojo属性值如果parameterType传输单个简单类型值${}括号中只能是value。第二章MyBatis参数详解
1. parameterType 简单数据类型 int double类型 String类型 long 简单的写法java.lang.Integer -- int integer Int Integer 都可以框架提供简写的方式。 POJO(JavaBean实体类)对象类型默认是不能简写可以配置。 User对象 POJO包装对象类型 包含更多的实体类 package cn.tx.domain;import java.io.Serializable;/*** * * * **/
public class QueryVo implements Serializable {// 自己属性private String name;// user属性private User user;// role属性private Role role;public String getName() {return name;}public void setName(String name) {this.name name;}public User getUser() {return user;}public void setUser(User user) {this.user user;}public Role getRole() {return role;}public void setRole(Role role) {this.role role;}
}// 测试包装类查询
public ListUser findByVo(QueryVo vo);!--包装类测试查询--
select idfindByVo parameterTypecom.qcbyjy.domain.QueryVo resultTypecom.qcbyjy.domain.Userselect * from user where username #{user.username}
/select
2. resultType 返回简单数据类型 int double long String 返回POJO数据类型 返回User对象类型 resultMap结果类型 resultType可以指定pojo将查询结果映射为pojo但需要pojo的属性名和sql查询的列名一致方可映射成功。 如果sql查询字段名和pojo的属性名不一致可以通过resultMap将字段名和属性名作一个对应关系 resultMap实质上还需要将查询结果映射到pojo对象中。 resultMap可以实现将查询结果映射为复杂类型的pojo比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。 !--演示resultMap配置--
select idfindUsers resultMapuserMapselect id _id,username _username,birthday _birthday,sex _sex,address _address from user
/select!--配置resultMap用来进行数据封装id唯一的名称用来被引用的type进行封装数据的类型--
resultMap iduserMap typecom.qcbyjy.domain.User!--propertyJavaBean中的属性column表中的字段--result propertyid column_id/result propertyusername column_username /result propertybirthday column_birthday /result propertysex column_sex /result propertyaddress column_address /
/resultMap第三章SqlMapConfig.xml配置文件
1. 定义properties标签的方式管理数据库的信息 把数据库的信息定义property标签中的方式在 properties 元素内直接定义 jdbc 相关属性如 jdbc.driver、jdbc.url 等这些属性在 dataSource 元素中通过 ${} 占位符使用实现了配置信息的集中管理。 ?xml version1.0 encodingUTF-8?
!DOCTYPE configuration PUBLIC -//mybatis.org//DTD Config 3.0//EN http://mybatis.org/dtd/mybatis-3-config.dtd
configurationpropertiesproperty namejdbc.driver valuecom.mysql.jdbc.Driver/property namejdbc.url valuejdbc:mysql:///mybatis_db/property namejdbc.username valueroot/property namejdbc.password valueroot//properties!-- 配置环境们 --environments defaultmysql!-- 配置具体的环境 --environment idmysql!-- 配置事务管理类型 --transactionManager typeJDBC/!-- 配置是否需要使用连接池POOLED使用UNPOOLED不使用 --dataSource typePOOLEDproperty namedriver value${jdbc.driver}/property nameurl value${jdbc.url}/property nameusername value${jdbc.username}/property namepassword value${jdbc.password}//dataSource/environment/environments!-- 加载映射的配置文件 --mappersmapper resourcemappers/UserMapper.xml//mappers
/configuration在项目中定义jdbc.properties属性文件存储数据库相关的信息统一管理在 SqlMapConfig.xml 中通过 properties resourcejdbc.properties/properties 引入使配置信息更易于维护。 jdbc.properties属性文件 jdbc.drivercom.mysql.jdbc.Driver
jdbc.urljdbc:mysql:///mybatis_db
jdbc.usernameroot
jdbc.passwordrootSqlMapConfig.xml的配置文件 在 environments 元素中设置事务管理类型和数据源类型数据源类型可选择使用连接池POOLED或不使用UNPOOLED。 元素加载映射文件将 UserMapper.xml 引入。 ?xml version1.0 encodingUTF-8?
!DOCTYPE configuration PUBLIC -//mybatis.org//DTD Config 3.0//EN http://mybatis.org/dtd/mybatis-3-config.dtd
configuration!-- properties resourcejdbc.properties/properties读取外部的配置文件resource文件的相对路径写法。例如jdbc.properties 或者 cn/tx/xxx/jdbc.properties--properties resourcejdbc.properties/properties!-- 配置环境们 --environments defaultmysql!-- 配置具体的环境 --environment idmysql!-- 配置事务管理类型 --transactionManager typeJDBC/!-- 配置是否需要使用连接池POOLED使用UNPOOLED不使用 --dataSource typePOOLEDproperty namedriver value${jdbc.driver}/property nameurl value${jdbc.url}/property nameusername value${jdbc.username}/property namepassword value${jdbc.password}//dataSource/environment/environments!-- 加载映射的配置文件 --mappersmapper resourcemappers/UserMapper.xml//mappers
/configuration2. 类型别名定义 MyBatis自已有类型别名的注册类咱们编写int或者integer通过注册可以找到java.lang.Integer 咱们自己也可以进行别名的注册 SqlMapConfig.xml的配置文件 !-- 定义别名 --
typeAliases!-- 把com.qcbyjy.domain.User使用user别名来显示别名user User USER都可以默认是忽略大写的 typeAlias typecom.qcbyjy.domain.User aliasuser/--!-- 针对com.qcbyjy.domain包下的所有的类都可以使用当前的类名做为别名 --package namecom.qcbyjy.domain/
/typeAliases UserMapper.xml的配置文件使用别名 !-- resultTypecom.qcbyjy.domain.User 原来是全路径resultTypeuser 现在使用的是别名的方式--
select idfindAll resultTypeuserselect * from user
/select