mybatis增删改查例子

合集下载

Mybatis-Plus增删改查

Mybatis-Plus增删改查

Mybatis-Plus 增删改查Mybatis-plus增删改查插⼊操作⽅法定义测试⽤例测试/*** 插⼊⼀条记录** @param entity 实体对象*/int insert(T entity);package com.pbteach.mp;import erMapper;import er;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testInsert(){User user = new User();user.setAge(20);user.setEmail("test@");user.setName("曹操");user.setUserName("caocao");user.setPassword("123456");int result = erMapper.insert(user); //返回的result 是受影响的⾏数,并不是⾃增后的idSystem.out.println("result = " + result);System.out.println(user.getId()); //⾃增后的id 会回填到对象中}}[main] [erMapper.insert]-[DEBUG] ==> Preparing: INSERT INTO tb_user ( id, user_name, password, name, age, email ) VALUES ( ?, ?, ?, ?, ?, ? )[main] [erMapper.insert]-[DEBUG] ==> Parameters: 1122045867793072130(Long), caocao(String), 123456(String), 曹操(String), 20(Integer), test@(String)[main] [erMapper.insert]-[DEBUG] <== Updates: 1[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@411291e5]result = 11122045867793072130可以看到,数据已经写⼊到了数据库,但是,id的值不正确,我们期望的是数据库⾃增长,实际是MP⽣成了id的值写⼊到了数据库。

fastmybatis案例

fastmybatis案例

fastmybatis案例fastmybatis是一款快速开发MyBatis项目的工具,借助该工具可以大幅度提高项目开发效率。

下面介绍一个fastmybatis的使用案例。

假设现在需要开发一个用户管理系统,需要实现用户的增删改查功能。

首先需要定义一个用户实体类,如下:```javapublic class User {private Long id;private String username;private String password;private Integer age;// 省略getter和setter方法}```然后在数据库中创建一个名为user的表,包含id、username、password、age四个字段。

接着在项目中引入fastmybatis的依赖,并配置数据源和MyBatis的配置文件。

在配置文件中定义一个名为UserMapper的Mapper接口,如下:```javapublic interface UserMapper extends BaseMapper<User, Long>{}```这里使用BaseMapper作为父接口,同时指定实体类和主键类型。

BaseMapper已经封装了常用的增删改查操作,可以直接使用。

接着在Service中定义方法,如下:```java@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic void addUser(User user) {userMapper.insert(user);}@Overridepublic void updateUser(User user) {userMapper.update(user);}@Overridepublic void deleteUser(Long id) {userMapper.deleteById(id);}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic List<User> getAllUsers() {return userMapper.selectAll();}}```可以看到,这里的实现非常简单,直接调用Mapper的方法即可。

springboot整合mybatis实现增删改查小案例

springboot整合mybatis实现增删改查小案例

springboot整合mybatis实现增删改查⼩案例⼀、springboot简单hello world1.1 使⽤springboot项⽬前提是必须学会使⽤maven,maven這⾥就不多说了⽹上招⼀⼤堆教程1.2 创建⼀个war包的maven项⽬,创建后在pox.xml添加如下jar1.3 创建⼀个springboot的程序⼊⼝启动类:如下package com.ibigsea.bootdao;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.transaction.annotation.EnableTransactionManagement;@SpringBootApplicationpublic class UserApplication {public static void main(String[] args) {SpringApplication.run(UserApplication.class, args);}}package com.ibigsea.bootdao.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("users")public class UserController {@RequestMapping("hello")public String hello(){return "Hello World";}}浏览器访问结果如下:⾄此⼀个简单的springboot的应⽤已完成,下⾯整合mybatis实现简单的增删改查案例⼆、springboot整合mybatis案例2.1 ⾸先需要在pox.xml导⼊jar 在hello world案例之上添加如下⼏个jar包</dependency>2.2 在src/main/resources⽬录下创建⼀个application.properties⽂件,内容如下2.3 entity类package com.ibigsea.bootdao.entity;import java.io.Serializable;public class User implements Serializable {private static final long serialVersionUID = 8809101560720973267L; private Integer id;private String userName;private Integer age;public User() {// TODO Auto-generated constructor stub}public User(String userName, Integer age) {super();erName = userName;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {public void setUserName(String userName) {erName = userName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";}}2.4 mapper接⼝类可以在类加上@Mapper注解也可以在springboot应⽤的程序⼊⼝类@MapperScan(“com.ibigsea.bootdao.mapper”) package com.ibigsea.bootdao.mapper;import java.util.List;import org.apache.ibatis.annotations.Mapper;import er;public interface UserMapper {/*** 新增* @param userint save(User user);/*** 根据Id查询* @param user* @return*/User selectById(Integer id);/*** 根据Id修改* @param user* @return*/int updateById(User user);/*** 删除* @param user* @return*/int deleteById(Integer id);/*** 查询所有* @param user* @return*/List<User> queryAll();/*** 根据username查询*/User findByName(String username); }<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd" ><mapper namespace="erMapper" ><insert id="save" parameterType="er">insert into user(username,age) values(#{userName,jdbcType=VARCHAR},#{age,jdbcType=NUMERIC})</insert><select id="selectById" resultType="er">select * from user where id = #{id,jdbcType=NUMERIC}</select><update id="updateById" parameterType="er"> update user setusername = #{userName,jdbcType=VARCHAR} ,age = #{age,jdbcType=NUMERIC}where id = #{id,jdbcType=NUMERIC}</update><delete id="deleteById">delete from user where id = #{id,jdbcType=NUMERIC}</delete><select id="queryAll" resultType="er">select * from user</select><select id="findByName" resultType="er">select * from user where username=#{userName}</select></mapper>2.6 业务接⼝类与2.4的mapper接⼝类内容⼀致2.7 业务接⼝类的实现package com.ibigsea.bootdao.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import er;import erMapper;import erService;@Transactional@Servicepublic class UserServiceImpl implements UserService{@Autowiredprivate UserMapper userMapper;@Overridepublic int save(User user) {int myuser= userMapper.save(user);//测试事务管理//int i =1/0;return myuser;}@Overridepublic User selectById(Integer id) {return userMapper.selectById(id);}@Overridepublic int updateById(User user) {return userMapper.updateById(user);}@Overridepublic int deleteById(Integer id) {return userMapper.deleteById(id);}@Overridepublic List<User> queryAll() {return userMapper.queryAll();}@Overridepublic User findByName(String username) {return userMapper.findByName(username);}}此处配置了事物管理需要在springboot⼊⼝类添加@EnableTransactionManagement 开启事物管理2.8 控制层package com.ibigsea.bootdao.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import er;import erService;@RestController@RequestMapping("users")public class UserController {@RequestMapping("hello")public String hello(){return "Hello World";}@RequestMapping("/add/{name}/{age}")public User insert(@PathVariable("name")String name,@PathVariable Integer age){userService.save(new User(name,age));return userService.findByName(name);}@RequestMapping("/findById/{id}")public User findById(@PathVariable("id") Integer id){return userService.selectById(id);}@RequestMapping("/deleteById/{id}")public void deleteById(@PathVariable("id") Integer id){userService.deleteById(id);}@RequestMapping("/updateById/{id}")public void updateById(@PathVariable("id") Integer id){User user = new User();user.setId(id);user.setAge(100);user.setUserName("xiaoguo");userService.updateById(user);}@RequestMapping("getUserList")public List<User> getUserList(){return userService.queryAll();}}2.9 spring boot 程序⼊⼝启动类package com.ibigsea.bootdao;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.transaction.annotation.EnableTransactionManagement;@SpringBootApplication@EnableTransactionManagement@MapperScan("com.ibigsea.bootdao.mapper")public class UserApplication {public static void main(String[] args) {SpringApplication.run(UserApplication.class, args);}}⾄此springboot整合mybatis整合完成,项⽬的⽬录结构如下:运⾏结果如下:。

MybatisPlus实现简单增删改查功能

MybatisPlus实现简单增删改查功能

MybatisPlus实现简单增删改查功能实现步骤:⼯具:IDEA数据库版本:mysql5.7⼀、环境搭建1.创建springboot项⽬pom.xml2.pom.xml : spring web、lombok mysql<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>3.添加mybatisplus依赖<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1.tmp</version></dependency>application.properties4.application.properties配置⽂件:⽤户名、密码、连接驱动、配置⽇志注意:mysql8 需要增加时区的配置 serverTimezone=GMT%2B8 东⼋区#mysql5 驱动不同ername=rootspring.datasource.password=123456spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver#配置⽇志mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl数据库数据#建表DROP TABLE IF EXISTS user;CREATE TABLE user(id BIGINT(20) NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年龄',email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (id));#插⼊数据DELETE FROM user;INSERT INTO user (id, name, age, email) VALUES(1, 'Jone', 18, 'test1@'),(2, 'Jack', 20, 'test2@'),(3, 'Tom', 28, 'test3@'),(4, 'Sandy', 21, 'test4@'),(5, 'Billie', 24, 'test5@');代码详解1.新建实体类Userlombok注解详解:@Data:⾃动⽣成get\set⽅法@AllArgsConstructor :有参⽅法@NoArgsConstructor:⽆参⽅法@TableId(value = “id”,type = IdType.AUTO) :给实体设置⾃增package com.sh.entity;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.context.annotation.Primary;import java.util.Date;@Data@AllArgsConstructor@NoArgsConstructorpublic class User {@TableId(value = "id",type = IdType.AUTO)private Integer id;private String name;private Integer age;private String email;private Date createTime;private Date updateTime;}2. 新建mapper包在mapper包⾥建UserMappe接⼝r 继承BaseMapper<实体类> package com.sh.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import er;import org.springframework.stereotype.Repository;@Repositorypublic interface UserMapper extends BaseMapper<User> {}3.创建控制层controller:新建UserController类package com.sh.controller;import er;import erMapper;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@RestControllerpublic class UserController {@Autowiredprivate UserMapper userMapper;//查询查询所以 null 就是没有条件@GetMapping("/selectUser")public List<User> getAll(){List<User> user = userMapper.selectList(null);return user;}//根据id查询@GetMapping("/selectById")public User selectUserById(){User user = userMapper.selectById(1);return user;}//根据多个id查询 Arrays.asList集合@GetMapping("/selectByIds")public List<User> selectUserByIds(){List<User> user = userMapper.selectBatchIds(Arrays.asList(1,2,3)); return user;}//添加@PostMapping("/insertUser")public Integer insertUsers(User user){Integer result = userMapper.insert(user);return result;}//修改根据id@PutMapping("/updateUser")public Integer updateUsers(User user){Integer result = userMapper.updateById(user);return result;}//删除根据id@DeleteMapping("/deleteUser")public Integer deleteUsers(Integer id){Integer result = userMapper.deleteById(id);return result;}}项⽬结构注意:添加,修改操作需要数据库和实体设置⾃增到此这篇关于MybatisPlus实现简单增删改查的⽂章就介绍到这了,更多相关MybatisPlus增删改查内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

springboot+Mybatis批量增删改查(java批量添加、修改带非空判断)

springboot+Mybatis批量增删改查(java批量添加、修改带非空判断)

springboot+Mybatis批量增删改查(java批量添加、修改带⾮空判断)1、批量添加--xml代码<insert id="insertBatchList" parameterType="java.util.List">INSERT INTO sw_rs_set_holdstandard (hold_createtime,hold_flag,company_id,hold_type,train_id,hold_level3,hold_level4)values<foreach collection="list" item="item" index="index" separator=","><trim prefix=" (" suffix=")" suffixOverrides="," >now(),1,#{panyIdbs,jdbcType=BIGINT}<if test="item.holdType!=null">,#{item.holdType,jdbcType=BIGINT}</if><if test="item.holdType==null">,0</if>,#{item.trainIdbs,jdbcType=BIGINT}<if test="item.holdLevel3!=null">,#{item.holdLevel3,jdbcType=BIGINT}</if><if test="item.holdLevel3==null">,0</if><if test="item.holdLevel4!=null">,#{item.holdLevel4,jdbcType=BIGINT}</if><if test="item.holdLevel4==null">,0</if></trim></foreach></insert>2、批量添加--调⽤/*** 批量添加*/int insertBatchList(List<SwRsSetHoldstandardEntity> list);3、批量修改--xml代码<update id="updateBatchList" parameterType="java.util.List">UPDATE sw_rs_set_holdstandard<trim prefix="set" suffixOverrides=","><trim prefix="hold_updatetime =case" suffix="end,"><foreach collection="list" item="item">when hold_id = #{item.holdId} then now()</foreach></trim><trim prefix="hold_level3 =case" suffix="end,"><foreach collection="list" item="item" index="index"><if test="item.holdLevel3!=null">when hold_id = #{item.holdId} then #{item.holdLevel3}</if></foreach></trim><trim prefix="hold_level4 =case" suffix="end,"><foreach collection="list" item="item"><if test="item.holdLevel4!=null">when hold_id = #{item.holdId} then #{item.holdLevel4}</if></foreach></trim></trim>where hold_id in<foreach collection="list" index="index" item="item" separator="," open="(" close=")">#{item.holdId}</foreach></update>4、批量修改--调⽤/*** 批量修改*/int updateBatchList(List<SwRsSetHoldstandardEntity> list);5、批量删除--xml<delete id="deleteByPrimaryKey" parameterType="java.util.List">delete from descriptionwhere idin<foreach collection="list" item="id" open="(" separator="," close=")">#{id}</foreach></delete>6、查询xml<select id="getHoldstandardList" parameterType="com.rxjy.modules.ku.entity.SwRsSetHoldstandardEntity" resultMap="BaseResultMap"> SELECTtp.train_level trainLevel,tp.train_id trainIdbs,tp.train_postname trainPostname,-1 companyIdbs,case hs.hold_type when 1 then '资源' when 2 then '客源' else '' end holdTypeName,ifnull(cp.co_name,'集团') coName,hs.*,<include refid="Base_Column_List"></include>from sw_rs_trainingrepository tpLEFT JOIN sw_rs_set_holdstandard hs on hs.train_id=tp.train_id and hs.hold_flag=1<if test="companyId!=null">and pany_id=#{companyId}</if><if test="holdType!=null">and hs.hold_type=#{holdType}</if>LEFT JOIN sw_bs_company cp on pany_id=pany_idwhere tp.train_isenable=1<if test="trainPostname!=null and trainPostname!=''">and tp.train_postname=#{trainPostname}</if>order by tp.train_rank asc</select>。

【Mybatis】mybatis开启Log4j日志、增删改查操作

【Mybatis】mybatis开启Log4j日志、增删改查操作

【Mybatis】mybatis开启Log4j⽇志、增删改查操作Mybatis⽇志(最常⽤的Log4j)# Global logging configurationlog4j.rootLogger=ERROR, stdout# MyBatis logging configuration...需要修改下⾯的⼀⾏.mybatis.example.BlogMapper=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderyout=org.apache.log4j.PatternLayoutyout.ConversionPattern=%5p [%t] - %m%n修改第四⾏:log4j.logger.⾃⼰程序的包名=TRACE例如.blb=TRACE**Mybatis增删改查dao层接⼝public interface UserDao {/*** 查询所有⽤户* @return*/List<User> getUsers();/*** 添加⽤户* @return*/void addUser(User user);/*** 删除⽤户* @return*/void delUserById(int id);void updateUserName(@Param("after") String after, @Param("id")int id);}映射配置⽂件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="erDao"><select id="getUsers" resultType="er">select * from userinfo</select><insert id="addUser" >INSERT INTO userinfo VALUES(null ,#{username},#{userpwd},#{typeid},#{userstatus})</insert><delete id="delUserById">DELETE FROM userinfo WHERE userid=#{id}</delete><update id="updateUserName">UPDATE userinfo SET username=#{after} WHERE userid=#{id};</update></mapper>使⽤注解的⽅式来映射使⽤注解的⽅式,就不⽤在xml中写<select id="getUsers" resultType="er">select * from userinfo</select>这样的语句了,⾮常⽅便,但是,复杂的SQL语句写在xml⽂件⾥⽅便维护!使⽤注解,⾮常简单public interface UserDao {/*** 查询所有⽤户* @return*/@Select("select * from userinfo")List<User> getUsers();/*** 添加⽤户* @return*/@Insert("INSERT INTO userinfo VALUES(null ,#{username},#{userpwd},#{typeid},#{userstatus})") void addUser(User user);/*** 删除⽤户* @return*/@Delete("DELETE FROM userinfo WHERE userid=#{id}")void delUserById(int id);@Update("UPDATE userinfo SET username=#{after} WHERE userid=#{id};")void updateUserName(@Param("after") String after, @Param("id")int id);}答疑@Update("UPDATE userinfo SET username=#{after} WHERE userid=#{id};")void updateUserName(@Param("after") String after, @Param("id")int id);写这种参数的时候要取别名@Param("别名"),不然获取不到参数报错。

mybatis xml update delete语句

mybatis xml update delete语句

mybatis xml update delete语句MyBatis是一种用于Java语言的持久化框架,通过XML配置文件进行SQL语句的编写。

其中,update和delete语句用于更新和删除数据库中的记录。

以下是MyBatis XML中编写update和delete语句的相关参考内容:1. Update语句:在MyBatis XML文件中,可以通过`<update>`标签来编写update语句。

以下是一个示例:```xml<update id="updateUser" parameterType="User">UPDATE userSET username = #{username}, password = #{password}WHERE id = #{id}</update>```- `<update>`标签用于定义一个update语句。

- `id`属性用于指定语句的唯一标识符。

- `parameterType`属性用于指定传入的参数类型,这里是User 类。

- `UPDATE user`部分指定要更新的表名为`user`,可以根据实际情况进行替换。

- `SET username = #{username}, password = #{password}`部分用于指定要更新的字段和字段值,通过`#{}`来引用参数值。

- `WHERE id = #{id}`部分用于指定要更新的记录的条件,通过`#{}`来引用参数值。

2. Delete语句:在MyBatis XML文件中,可以通过`<delete>`标签来编写delete语句。

以下是一个示例:```xml<delete id="deleteUser" parameterType="int">DELETE FROM userWHERE id = #{id}</delete>```- `<delete>`标签用于定义一个delete语句。

mybatis抽取基类BaseMapper增删改查的实现

mybatis抽取基类BaseMapper增删改查的实现

mybatis抽取基类BaseMapper增删改查的实现⽬录准备⼯作:1:数据库表2:准备实体类步骤1:编写⼯具类Tools:作⽤:⽤于驼峰和数据库字段的转换步骤2:⾃定义两个注解,分别⽤于类字段的排除和字义主键步骤3:⾃定义动态sql⽣成类BaseSqlProvider<T>步骤4:编写BaseMapper基类接⼝举例:⽬前项⽬当中使⽤mapper.xml⽂件⽅式对数据库进⾏操作,但是每个⾥边都有增/删/改/查,为了⽅便开发,把这些公共的代码提取出来,不⽤当做基类,不⽤每个Mapper⽂件都写了准备⼯作:1:数据库表CREATE TABLE `t_permission` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '权限ID',`type` int(11) NOT NULL COMMENT '权限类型',`name` varchar(255) NOT NULL COMMENT '权限名称',PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COMMENT='权限表';2:准备实体类public class TPermissionEntity {@PrimaryKey //下⾯步骤2中⾃定义注解private Integer id;//权限IDprivate Integer type;//权限类型private String name;//权限名称//省略了get,set⽅法....}步骤1:编写⼯具类Tools:作⽤:⽤于驼峰和数据库字段的转换因为类的名称⽤的是驼峰命名,所以这⾥需要转换⼀下import java.util.regex.Matcher;import java.util.regex.Pattern;/** 驼峰名称和下划线名称的相互转换*/public class Tool {private static Pattern linePattern = pile("_(\\w)");/** 下划线转驼峰 */public static String lineToHump(String str) {str = str.toLowerCase();Matcher matcher = linePattern.matcher(str);StringBuffer sb = new StringBuffer();while (matcher.find()) {matcher.appendReplacement(sb, matcher.group(1).toUpperCase());}matcher.appendTail(sb);return sb.toString();}private static Pattern humpPattern = pile("[A-Z]");/** 驼峰转下划线,效率⽐上⾯⾼ */public static String humpToLine(String str) {Matcher matcher = humpPattern.matcher(str);StringBuffer sb = new StringBuffer();while (matcher.find()) {matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());}matcher.appendTail(sb);return sb.toString();}}步骤2:⾃定义两个注解,分别⽤于类字段的排除和字义主键@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Exclude {}@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface PrimaryKey {String value() default "";}步骤3:⾃定义动态sql⽣成类BaseSqlProvider<T>作⽤:根据传⼊的对象动态获取表名和字段名⽣成动态的sql语句,再执⾏@Insert,@Select,@update,@Delete是直接配置SQL语句,⽽@InsertProvider,@UpdateProvider,@SelectProvider,@DeleteProvider则是通过SQL⼯⼚类及对应的⽅法⽣产SQL语句import ng.reflect.Field;import java.util.ArrayList;import java.util.List;import org.apache.ibatis.annotations.Options;import org.apache.ibatis.jdbc.SQL;import mon.utils.Tool;public class BaseSqlProvider<T> {@Optionspublic String add(T bean) {SQL sql = new SQL();Class clazz = bean.getClass();String tableName = clazz.getSimpleName();String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);sql.INSERT_INTO(realTableName);List<Field> fields = getFields(clazz);for (Field field : fields) {field.setAccessible(true);String column = field.getName();System.out.println("column:" + Tool.humpToLine(column));sql.VALUES(Tool.humpToLine(column), String.format("#{" + column + ",jdbcType=VARCHAR}"));}return sql.toString();}public String delete(T bean) {SQL sql = new SQL();Class clazz = bean.getClass();String tableName = clazz.getSimpleName();String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1); sql.DELETE_FROM(realTableName);List<Field> primaryKeyField = getPrimarkKeyFields(clazz);if (!primaryKeyField.isEmpty()) {for (Field pkField : primaryKeyField) {pkField.setAccessible(true);sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));}} else {sql.WHERE(" 1= 2");throw new RuntimeException("对象中未包含PrimaryKey属性");}return sql.toString();}private List<Field> getPrimarkKeyFields(Class clazz) {List<Field> primaryKeyField = new ArrayList<>();List<Field> fields = getFields(clazz);for (Field field : fields) {field.setAccessible(true);PrimaryKey key = field.getAnnotation(PrimaryKey.class);if (key != null) {primaryKeyField.add(field);}}return primaryKeyField;}private List<Field> getFields(Class clazz) {List<Field> fieldList = new ArrayList<>();Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {field.setAccessible(true);Exclude key = field.getAnnotation(Exclude.class);if (key == null) {fieldList.add(field);}}return fieldList;}public String get(T bean) {SQL sql = new SQL();Class clazz = bean.getClass();String tableName = clazz.getSimpleName();String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1); sql.SELECT("*").FROM(realTableName);List<Field> primaryKeyField = getPrimarkKeyFields(clazz);if (!primaryKeyField.isEmpty()) {for (Field pkField : primaryKeyField) {pkField.setAccessible(true);sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));}} else {sql.WHERE(" 1= 2");throw new RuntimeException("对象中未包含PrimaryKey属性");}System.out.println("getSql:"+sql.toString());return sql.toString();}public String update(T bean) {SQL sql = new SQL();Class clazz = bean.getClass();String tableName = clazz.getSimpleName();String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);sql.UPDATE(realTableName);List<Field> fields = getFields(clazz);for (Field field : fields) {field.setAccessible(true);String column = field.getName();if (column.equals("id")) {continue;}System.out.println(Tool.humpToLine(column));sql.SET(Tool.humpToLine(column) + "=" + String.format("#{" + column + ",jdbcType=VARCHAR}")); }List<Field> primaryKeyField = getPrimarkKeyFields(clazz);if (!primaryKeyField.isEmpty()) {for (Field pkField : primaryKeyField) {pkField.setAccessible(true);sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));}} else {sql.WHERE(" 1= 2");throw new RuntimeException("对象中未包含PrimaryKey属性");}System.out.println("updateSql:"+sql.toString());return sql.toString();}}步骤4:编写BaseMapper基类接⼝public interface BaseMapper<T> {//新增⼀条数据@InsertProvider(method = "add",type=BaseSqlProvider.class)@Options(useGeneratedKeys=true)public int add(T bean);//根据主键删除⼀条数据@DeleteProvider(method = "delete",type=BaseSqlProvider.class)public int delete(T bean);//根据主键获取⼀条数据@SelectProvider(method = "get",type=BaseSqlProvider.class)public T get(T bean);//修改⼀条数据@UpdateProvider(method = "update",type=BaseSqlProvider.class)public int update(T bean);}说明:@InsertProvider注解中的type指明⾃定义的SQL⼯⼚类,method是⼯⼚类⾥对应的⽅法,⽅法返回的是对⽅的sql语句到这⾥基类以及它的配置就完成了,接下来,可以使⽤了举例:编写⼀个TPermissionMapper接⼝,实现BaseMapper类,并传⼊⼀个泛型参数,此时这个TPermissionMapper接⼝已经具备了,BaseMapper中基本的增/删/改/查功能.同时TPermissionMapper还可以再写⾃⼰独有的⽅法和mapper.xml⽂件对功能进⾏扩展public interface TPermissionMapper extends BaseMapper<TPermissionEntity>{//List<TPermissionEntity> queryByPage();}在controller当中的应⽤:@Controllerpublic class LoginController {@Autowiredprivate TPermissionMapper tPermissionMapper;//新增@ResponseBody@RequestMapping(value = "/add")public Integer add() {TPermissionEntity permissionEntiry = new TPermissionEntity();permissionEntiry.setName("test");permissionEntiry.setType(3);Integer num = tPermissionMapper.add(permissionEntiry);return num;}//修改@ResponseBody@RequestMapping(value = "/update")public Integer update() {TPermissionEntity permissionEntiry = new TPermissionEntity();permissionEntiry.setId(23);permissionEntiry.setName("test");permissionEntiry.setType(3);Integer num = tPermissionMapper.update(permissionEntiry);return num;}//查询@ResponseBody@RequestMapping(value = "/query")public TPermissionEntity query() {TPermissionEntity tPermissionEntity = new TPermissionEntity();tPermissionEntity.setId(23);tPermissionEntity= (TPermissionEntity) tPermissionMapper.get(tPermissionEntity);return tPermissionEntity;}//删除@ResponseBody@RequestMapping(value = "/delete")public Integer delete() {TPermissionEntity permissionEntiry = new TPermissionEntity();permissionEntiry.setId(22);Integer num = tPermissionMapper.delete(permissionEntiry);return num;}}到此这篇关于mybatis抽取基类BaseMapper增删改查的实现的⽂章就介绍到这了,更多相关mybatis BaseMapper增删改查内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

如何在IDEA中使用mybatis创建项目并进行增删改查操作

如何在IDEA中使用mybatis创建项目并进行增删改查操作

如何在IDEA中使⽤mybatis创建项⽬并进⾏增删改查操作1、新建⼀个项⽬;2、导⼊相关的依赖包;3、配置mybatis主配置⽂件,连接信息和mapper位置等;①mybatis主配置⽂件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN""/dtd/mybatis-3-config.dtd"><configuration><!--引⼊jdbc.properties配置⽂件--><properties resource="jdbc.properties"></properties><!--mybatis设置项--><settings><!--开启⽇志,将⽇志信息打印到控制台--><setting name="logImpl" value="STDOUT_LOGGING" /><!--开启缓存,默认开启--><setting name="cacheEnabled" value="true"/><!--设置延迟加载--><setting name="lazyLoadingEnabled" value="true"/><!----><setting name="aggressiveLazyLoading" value="false"/></settings><!-- 配置实体类别名 --><typeAliases><!-- 配置实体类所在包 --><package name="com.seecen.mybatis3.pojo"/></typeAliases><!----><!--数据库连接池信息--><environments default="oracledb"><environment id="oracledb"><!--配置事务管理⽅式,指定为使⽤jdbc的事务--><transactionManager type="jdbc"></transactionManager><!--指定数据源,type pooled指定为连接池--><dataSource type="pooled"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${ername}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!-- 配置mapper.xml⽂件位置 --><mappers><!--指定mapper⽂件所在包--><package name="com.seecen.mybatis3.mapper"/></mappers></configuration>②连接信息jdbc:properties;jdbc.driver=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin:@localhost:1521:xeername=sc2001jdbc.password=sun#\u9A71\u52A8jar\u5305\u7684\u4F4D\u7F6E,\u5177\u4F53\u7684\u8DEF\u5F84\u3002\u9006\u5411\u751F\u6210\u4EE3\u7801\u65F6\u4F7F\u7528 driverClassPath=C:\\Users\\Administrator\\.m2\\repository\\com\\oracle\\ojdbc6\\11.2.0.3.0\\ojdbc6-11.2.0.3.0.jar③配置配置⽂件generatorConfig.xml;<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN""/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration><!--加载jdbc.properties配置⽂件--><properties resource="jdbc.properties" /><!--配置驱动jar包的位置--><classPathEntry location="${driverClassPath}" /><!--context:⽣成⼀组对象的环境id:必选,上下⽂id,⽤于在⽣成错误时提⽰defaultModelType:指定⽣成对象的样式1,conditional:类似hierarchical;2,flat:所有内容(主键,blob)等全部⽣成在⼀个对象中;3,hierarchical:主键⽣成⼀个XXKey对象(key class),Blob等单独⽣成⼀个对象,其他简单属性在⼀个对象中(record class)targetRuntime:1,MyBatis3:默认的值,⽣成基于MyBatis3.x以上版本的内容,包括XXXBySample;2,MyBatis3Simple:类似MyBatis3,只是不⽣成XXXBySample;introspectedColumnImpl:类全限定名,⽤于扩展MBG--><context id="context1" targetRuntime="MyBatis3"><!-- genenat entity时,⽣成toString --><plugin type="org.mybatis.generator.plugins.ToStringPlugin"/><!-- generate entity时,⽣成serialVersionUID --><plugin type="org.mybatis.generator.plugins.SerializablePlugin"/><!--不⽣成注释--><commentGenerator><property name="suppressAllComments" value="true" /></commentGenerator><!--配置数据库连接信息--><jdbcConnection driverClass="${jdbc.driver}"connectionURL="${jdbc.url}" userId="${ername}" password="${jdbc.password}" /><!-- java模型创建器,是必须要的元素负责:1,key类(见context的defaultModelType);2,java类;3,查询类targetPackage:⽣成的类要放的包,真实的包受enableSubPackages属性控制;targetProject:⽬标项⽬,指定⼀个存在的⽬录下,⽣成的内容会放到指定⽬录中,如果⽬录不存在,MBG不会⾃动建⽬录--><javaModelGenerator targetPackage="com.seecen.mybatis.pojo"targetProject="src/main/java"><!-- 设置是否在getter⽅法中,对String类型字段调⽤trim()⽅法 --><property name="trimStrings" value="true" /></javaModelGenerator><!-- ⽣成SQL map的XML⽂件⽣成器,注意,在Mybatis3之后,我们可以使⽤mapper.xml⽂件+Mapper接⼝(或者不⽤mapper接⼝),或者只使⽤Mapper接⼝+Annotation,所以,如果 javaClientGenerator配置中配置了需要⽣成XML的话,这个元素就必须配置 targetPackage/targetProject:同javaModelGenerator--><sqlMapGenerator targetPackage="com.seecen.mybatis.mapper"targetProject="src/main/java"></sqlMapGenerator><!-- 对于mybatis来说,即⽣成Mapper接⼝,注意,如果没有配置该元素,那么默认不会⽣成Mapper接⼝targetPackage/targetProject:同javaModelGeneratortype:选择怎么⽣成mapper接⼝(在MyBatis3/MyBatis3Simple下):1,ANNOTATEDMAPPER:会⽣成使⽤Mapper接⼝+Annotation的⽅式创建(SQL⽣成在annotation中),不会⽣成对应的XML;2,MIXEDMAPPER:使⽤混合配置,会⽣成Mapper接⼝,并适当添加合适的Annotation,但是XML会⽣成在XML中;3,XMLMAPPER:会⽣成Mapper接⼝,接⼝完全依赖XML;注意,如果context是MyBatis3Simple:只⽀持ANNOTATEDMAPPER和XMLMAPPER--><javaClientGenerator targetPackage="com.seecen.mybatis.mapper"targetProject="src/main/java" type="XMLMAPPER" /><table tableName="t_course" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"></table></context></generatorConfiguration>这三个⽂件放⼊资源⽬录下⾯;我的⽬录是这样的,仅供参考:4、在pojo中创建⼀个Product.java的实体类⽂件;package com.seecen.mybatis3.pojo;import java.io.Serializable;public class Product implements Serializable {private Integer id;private String name;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}@Overridepublic String toString() {return"Product{" +"id=" + id +", name='" + name + '\'' +'}';}}4、编写Mapper对应的mapper.xml⽂件和接⼝,定义接⼝⽅法对应的sql语句;ProductMapper⽂件和ProductMapper.xml⽂件:package com.seecen.mybatis3.mapper;import com.seecen.mybatis3.pojo.Product;import java.util.List;public interface ProductMapper {int insert(Product product);int deleteById(Integer id);int update(Product product);Product selectById(Integer id);List<Product> selectAll();}<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.seecen.mybatis3.mapper.ProductMapper"><insert id="insert" parameterType="Product"><selectKey keyProperty="id" order="BEFORE" resultType="integer">select p_pro.nextval from dual</selectKey>insert into Product(id,name) values(#{id},#{name})</insert><update id="update" parameterType="Product">update Product set name = #{name} where id=#{id}</update><delete id="deleteById">delete from Product where id=#{id}</delete><select id="selectById" parameterType="integer" resultType="Product">select * from Product where id=#{id}</select><select id="selectAll" resultType="Product">select * from Product</select></mapper>5、编写dao层访问接⼝Mapper,⽤来定义数据库操作⽅法;import com.seecen.mybatis3.mapper.ProductMapper;import com.seecen.mybatis3.pojo.Product;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.InputStream;import java.util.List;public class ProductTest {@Testpublic void Test() throws IOException {InputStream is= Resources.getResourceAsStream("mybatis.xml");SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession=sqlSessionFactory.openSession();ProductMapper mapper=sqlSession.getMapper(ProductMapper.class);//插⼊⼀条数据Product product=new Product();product.setName("三只松⿏");int count=mapper.insert(product);System.out.println("插⼊记录数:"+count);System.out.println(product);//删除⼀条记录int count1=mapper.deleteById(1);System.out.println(count1);//查询⼀条记录Product product1=mapper.selectById(2);System.out.println(product1);//修改⼀条记录product1.setName("⼀包薯⽚");int i=mapper.update(product1);System.out.println("修改记录数:"+i);//查询所有的信息List<Product> products=mapper.selectAll();for (Product product2:products){System.out.println(product2);}mit();sqlSession.close();is.close();}}最后,⼀定要多注意⼀些语法的规范或者要试着去查看错误信息,以便更好的修改错误。

总结一下mybatis对多对多查询与增删改查的心得

总结一下mybatis对多对多查询与增删改查的心得

总结一下mybatis对多对多查询与增删改查的心得引言在实际的开发中,多对多关联关系是经常遇到的问题,而m yba t is作为一款高效的持久层框架,为我们提供了便捷的解决方案。

本文将总结一下通过m yb at is对多对多关系进行查询和增删改查的心得。

查询多对多关系在m yb at is中,查询多对多关系可以通过嵌套查询和关联表查询来实现。

嵌套查询嵌套查询是通过在映射文件中定义多个查询语句,并通过r esu l tM ap来关联结果,从而实现多对多关系的查询。

具体步骤如下:1.在映射文件中定义多个s el ec t语句,分别查询两个关联表的数据。

2.使用\<re su lt Map>标签定义一个结果映射,包括两个关联表的字段。

3.在主查询语句中使用\<co ll ec ti on>标签来引用结果映射和关联查询语句。

4.使用联合结果映射来获取最终查询结果。

关联表查询关联表查询是通过多表联查来实现多对多关系的查询。

具体步骤如下:1.在映射文件中编写多表联查的SQ L语句,使用J OI N语句关联两个关联表。

2.在\<s el ec t>标签中使用\<re su lt Ma p>定义结果映射,包括两个关联表的字段。

3.在J av a代码中编写相应的Ma pp er接口和Ma pp er.x ml文件。

4.调用Ma pp er接口中的方法来执行查询操作。

增删改查多对多关系m y ba ti s对多对多关系的增删改查操作也是通过多表关联来实现的。

增加记录要增加多对多关系的记录,需要进行以下操作:1.在映射文件中定义插入操作的SQ L语句,插入关联表的数据。

2.在J av a代码中编写相应的Ma pp er接口和Ma pp er.x ml文件。

3.调用Ma pp er接口中的方法来执行插入操作。

删除记录要删除多对多关系的记录,需要进行以下操作:1.在映射文件中定义删除操作的SQ L语句,删除关联表的数据。

MybatisPlus:特点,快速入门,lombok的使用,常用注解,常用的增删改查,自动代码生成

MybatisPlus:特点,快速入门,lombok的使用,常用注解,常用的增删改查,自动代码生成

MybatisPlus:特点,快速⼊门,lombok的使⽤,常⽤注解,常⽤的增删改查,⾃动代码⽣成MybatisPlus课堂讲义SSH:Spring+Struts2+HibernateSSM: Spring+springmvc+mybatis⽬标:了解mybatisplus的特点能够掌握mybatisplus快速⼊门能够掌握mybatisplus常⽤注解能够掌握mybatisplus常⽤的增删改查能够掌握mybatisplus⾃动代码⽣成1. 概述•MyBatis-Plus(简称 MP)是⼀个 MyBatis 的增强⼯具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提⾼效率⽽⽣。

版本<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.4.0</version></dependency>2. 快速⼊门SpringBoot 整合 MyBatis-Plus,并实现根据Id查询功能。

①数据库环境准备②创建SpringBoot⼯程,引⼊MyBatis-Plus起步依赖③编写DataSource相关配置④编写mapper⑤测试2.1 数据库环境准备详见附件2.2 创建SpringBoot⼯程,引⼊MyBatis-Plus起步依赖<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.4.RELEASE</version><relativePath/><!-- lookup parent from repository --></parent><properties><java.version>1.8</java.version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- mysql 驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.26</version></dependency><!-- lombok ,⾃动⽣成get,Set ⽅法--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--mybatisplus起步依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.0</version></dependency></dependencies>1,在IDEA的插件中安装Lombok插件:settings-->plugins>搜索lombok然后安装重启IDEA 2,在依赖中引⼊lombok依赖:<!-- lombok ,⾃动⽣成get,Set ⽅法--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>3,在实体中使⽤相关的注解:帮我们减化开发2.3 编写DataSource相关配置# datasourcespring:datasource:url: jdbc:mysql:///mpusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver2.4 编码编写mapper/*** 使⽤mp定义Mapper,需要让Mapper接⼝继承 BaseMapper接⼝。

SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑

SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑

SpringBoot+MyBatis中⾃动根据@Table注解和@Column注解⽣成增删改查逻辑习惯使⽤jpa操作对象的⽅式,现在⽤mybatis有点不习惯。

其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO。

没办法,⾃⼰搞喽!这⾥主要是实现了通过代码⾃动⽣成mybatis的增删改查语句,并注册到SqlSessionFactory中,并没有⽣成xml⽂件,不⽣成mapper⽂件。

只是在项⽬启动的时候⾃动⽣成,配置到SqlSessionFactory中,下⼀次启动后⾃动根据model⾃动⽣成相关逻辑。

所以不必担⼼表结构修改需要改⼀⼤堆⽂件。

使⽤了此⽅法只需要改model⽂件就可以了。

注意:model必须添加@Table注解,对应的列也必须添加@Column注解(javax)。

思路:在项⽬启动时mybatis默认配置运⾏结束后添加⾃定义配置@Configuration@AutoConfigureAfter(MybatisAutoConfiguration.class)public class MyBatisTypeMapScannerConfig {private Logger log = Logger.getLogger(MyBatisTypeMapScannerConfig.class);public MyBatisTypeMapScannerConfig(ApplicationContext applicationContext, SqlSessionFactory sqlSessionFactory) {在配置中可以获取SqlSessionFactory,看到这⾥,已经结束了。

剩下的都是不重要细节。

1.读取项⽬下的model(包含@table注解的类)List<Class<?>> list = ClassUtil.getClassesWithAnnotation(Table.class);2.读取model下的字段(根据@Column注解)Map<String, Map<String, Object>> cols = ClassUtil.getColumnRelation(clas);3.根据table和column信息配置resultmap,mapperEnd;代码: MyBatisTypeMapScannerConfigimport java.io.ByteArrayInputStream;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;import javax.persistence.Table;import mons.logging.Log;import mons.logging.LogFactory;import org.apache.ibatis.builder.xml.XMLMapperBuilder;import org.apache.ibatis.mapping.ResultMap;import org.apache.ibatis.mapping.ResultMapping;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.tomcat.util.buf.StringUtils;import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Configuration;import com.esri.rest.util.ClassUtil;/*** ⾃动根据@Table注解和@Column注解添加mybatis中的resultmap配置,* 此配置⽣效后不需要在mapper.xml中⼿动添加resultmap,⾃动添加的resultmap的ID为类的全路径名* <p>* Title: MyBatisTypeMapScannerConfig.java* </p>* <p>* Description:* </p>** @author lichao1* @date 2018年12⽉4⽇* @version 1.0*/@Configuration@AutoConfigureAfter(MybatisAutoConfiguration.class)public class MyBatisTypeMapScannerConfig {protected final Log log = LogFactory.getLog(getClass());public MyBatisTypeMapScannerConfig(ApplicationContext applicationContext, SqlSessionFactory sqlSessionFactory) {log.debug("⾃动添加resultMap");org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();// ResultMap rm = new ResultMap.Builder(configuration, id, type,// null).build();// configuration.addResultMap(rm);// 获取默认包下的所有包含@Table注解的类List<Class<?>> list = ClassUtil.getClassesWithAnnotation(Table.class);for (Class<?> clas : list) {System.out.println(clas);Map<String, Map<String, Object>> cols = ClassUtil.getColumnRelation(clas);ResultMap rm = new ResultMap.Builder(configuration, clas.getName(), clas,getResultMapping(configuration, cols)).build();configuration.addResultMap(rm);List<ResultMap> resultMaps = new ArrayList<ResultMap>();resultMaps.add(rm);Table table = clas.getAnnotation(Table.class);String tableName = ();String allColum = getColumListString(cols);// select// String sql = " select " + allColum + " from " + tableName;// SqlSource sqlSource = new RawSqlSource(configuration, sql, clas);// Builder builder = new MappedStatement.Builder(configuration,// clas.getName() + ".select", sqlSource,// SqlCommandType.SELECT);// builder.resultMaps(resultMaps);// MappedStatement ms = builder.build();// configuration.addMappedStatement(ms);InputStream inputStream = createXml(clas, cols);XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, clas.getName() + ".auto",configuration.getSqlFragments());mapperParser.parse();}log.debug("⾃动添加resultMap");}private InputStream createXml(Class<?> clas, Map<String, Map<String, Object>> cols) {StringBuilder builder = new StringBuilder();String name = clas.getName();Table table = clas.getAnnotation(Table.class);String tableName = ();String allColum = getColumListString(cols);builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");builder.append("<!DOCTYPE mapper PUBLIC \"-////DTD Mapper 3.0//EN\" \"/dtd/mybatis-3-mapper.dtd\" >"); builder.append("<mapper namespace=\"" + name + "\" >");Set<String> keys = cols.keySet();String[] keyArr = new String[keys.size()];keys.toArray(keyArr);/****************** 查询 start ***************/builder.append("<select id=\"" + name + ".select\" resultMap=\"" + name + "\" >");builder.append("SELECT " + allColum + " FROM " + tableName + " WHERE 1=1 ");// builder.append(" <if test=\"id != null\"> and id like #{id} </if>");// 查询条件builder.append(createLikelySql(keyArr, clas, cols));// 排序builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");// 分页builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");/****************** 查询 end ***************//****************** 计数 start ***************/builder.append("<select id=\"" + name + ".count\" resultType=\"long\" >");builder.append("SELECT count(*) count FROM " + tableName + " WHERE 1=1 ");builder.append(createLikelySql(keyArr, clas, cols));builder.append("</select>");/****************** 计数 end ***************//****************** 精确查询 start ***************/builder.append("<select id=\"" + name + ".selectexactly\" resultMap=\"" + name + "\" >");builder.append("SELECT " + allColum + " FROM " + tableName + " WHERE 1=1 ");// builder.append(" <if test=\"id != null\"> and id like #{id} </if>");// 查询条件builder.append(createExactlySql(keyArr, clas, cols));// 排序builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");// 分页builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");/****************** 精确查询 end ***************//****************** 精确计数 start ***************/builder.append("<select id=\"" + name + ".countexactly\" resultType=\"long\" >");builder.append("SELECT count(*) count FROM " + tableName + " WHERE 1=1 ");builder.append(createExactlySql(keyArr, clas, cols));builder.append("</select>");/****************** 精确计数 end ***************//****************** ⾃定义条件语句查询 start ***************/builder.append("<select id=\"" + name + ".selectwhere\" resultMap=\"" + name + "\" >");builder.append("SELECT " + allColum + " FROM " + tableName + " ");// 查询条件builder.append(" <if test=\"WHERESTR != null\"> WHERE ${WHERESTR} </if>");// 排序builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");// 分页builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");/****************** ⾃定义条件语句查询 end ***************//****************** ⾃定义条件语句计数 start ***************/builder.append("<select id=\"" + name + ".countwhere\" resultType=\"long\" >");builder.append("SELECT count(*) count FROM " + tableName + " ");// 查询条件builder.append(" <if test=\"WHERESTR != null\"> WHERE ${WHERESTR} </if>");builder.append("</select>");/****************** ⾃定义条件语句计数 end ***************//****************** 删除 start ***************/builder.append("<delete id=\"" + name + ".delete\" parameterType=\"ng.String\" >");builder.append(" DELETE FROM " + tableName + " WHERE id =#{id} ");builder.append("</delete>");/****************** 删除 end ***************//****************** 批量删除 start ***************/builder.append("<delete id=\"" + name + ".deletebatch\" >");builder.append(" DELETE FROM " + tableName + " WHERE 1=1 ");builder.append(createExactlySql(keyArr, clas, cols));builder.append("</delete>");/****************** 批量删除 end ***************//****************** 更新 start ***************/builder.append("<update id=\"" + name + ".update\" parameterType=\"" + name + "\" >");builder.append("UPDATE " + tableName + " SET ");for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];Map<String, Object> obj = cols.get(key);builder.append(" " + (String) obj.get("dbname") + " = #{" + key + "}");if (i < (keyArr.length - 1)) {builder.append(",");}}builder.append(" WHERE id =#{id} ");builder.append("</update>");/****************** 更新 end ***************//****************** 按需更新 start ***************/builder.append("<update id=\"" + name + ".updatesection\" parameterType=\"" + name + "\" >");builder.append("UPDATE " + tableName + " SET ");for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];Map<String, Object> obj = cols.get(key);// builder.append(" " + (String) obj.get("dbname") + " = #{" + key +// "}");if (!"id".equals(key)) {builder.append(" <if test=\"_parameter.containsKey('" + key + "')\">" + (String) obj.get("dbname") + " = #{" + key + "} , </if>");// builder.append(" " + (String) obj.get("dbname") + " = #{" + key + "} , ");}}builder.append(" id = #{id} ");builder.append(" WHERE id =#{id} ");builder.append("</update>");/****************** 按需更新 end ***************//****************** 插⼊ start ***************/builder.append("<insert id=\"" + name + ".insert\" parameterType=\"" + name + "\" >");builder.append("insert INTO " + tableName + " (" + allColum + ") VALUES");builder.append("(" + getColumListString2(cols, "#{", "}") + ") ");builder.append("</insert>");/****************** 插⼊ end ***************/builder.append("</mapper>");InputStream is = new ByteArrayInputStream(builder.toString().getBytes());return is;}private String createListXml() {StringBuilder builder = new StringBuilder();return builder.toString();}/*** ⽣成查询条件语句** @param keyArr* @param clas* @param cols* @return*/private String createLikelySql(String[] keyArr, Class<?> clas, Map<String, Map<String, Object>> cols) {StringBuilder builder = new StringBuilder();for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];Map<String, Object> obj = cols.get(key);try {Class t = (Class) obj.get("type");if (t == String.class) {// String 类型⾃动⽀持like '%' || #name# || '%'builder.append(" <if test=\"" + key + " != null\"> and " + (String) obj.get("dbname")+ " like '%'||#{" + key + "}|| '%' </if>");} else {builder.append(" <if test=\"" + key + " != null\"> and " + (String) obj.get("dbname") + " = #{"+ key + "} </if>");}} catch (Exception e) {(obj);(key);(clas.getName());}}return builder.toString();}private String createExactlySql(String[] keyArr, Class<?> clas, Map<String, Map<String, Object>> cols) { StringBuilder builder = new StringBuilder();for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];Map<String, Object> obj = cols.get(key);builder.append(" <if test=\"" + key + " != null\"> and " + (String) obj.get("dbname") + " = #{" + key + "} </if>"); }return builder.toString();}/*** 获取表内字段** @param cols* @return*/private String getColumListString(Map<String, Map<String, Object>> cols) {return getColumListString(cols, "", "");}private String getColumListString(Map<String, Map<String, Object>> cols, String pre, String end) {pre = pre == null ? "" : pre;end = end == null ? "" : end;Set<String> keys = cols.keySet();String[] keyArr = new String[keys.size()];String[] nameArr = new String[keys.size()];keys.toArray(keyArr);for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];Map<String, Object> obj = cols.get(key);if (((String) obj.get("dbname")).equals("update_date")) {("key");}nameArr[i] = pre + (String) obj.get("dbname") + end;}return StringUtils.join(nameArr);}private String getColumListString2(Map<String, Map<String, Object>> cols) {return getColumListString2(cols, "", "");}private String getColumListString2(Map<String, Map<String, Object>> cols, String pre, String end) {pre = pre == null ? "" : pre;end = end == null ? "" : end;Set<String> keys = cols.keySet();String[] keyArr = new String[keys.size()];String[] nameArr = new String[keys.size()];keys.toArray(keyArr);for (int i = 0; i < keyArr.length; i++) {String key = keyArr[i];nameArr[i] = pre + key + end;}return StringUtils.join(nameArr);}/*** 根据@Column注解⽣成字段映射关系** @param configuration* @param Map<String,* Map<String, Object>> cols* @return*/private List<ResultMapping> getResultMapping(org.apache.ibatis.session.Configuration configuration,Map<String, Map<String, Object>> cols) {List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();System.out.println(cols);Set<String> keys = cols.keySet();String[] keyArr = new String[keys.size()];keys.toArray(keyArr);for (String key : keyArr) {String property;String column;Object javaType;Map<String, Object> map = cols.get(key);property = key;column = (String) map.get("dbname");javaType = map.get("type");ResultMapping mapping = new ResultMapping.Builder(configuration, property, column, (Class<?>) javaType) .build();resultMappings.add(mapping);}return resultMappings;}}应⽤CommonDaoimpl/*** CommonDaoimpl* <p>* Title: CommonDaoimpl.java* </p>* <p>* Description:* </p>** @author lichao1* @date 2018年11⽉19⽇* @version 1.0* @param <T>* @param <ID>*/@Repositorypublic class CommonDaoimpl<T, ID extends Serializable> implements ICommonDao<T, ID> {@PersistenceContextprivate EntityManager entityManager;@Autowiredpublic SqlSessionFactory sqlSessionFactory;protected <T> String getStatement(Class<T> clazz, String prefix) {String entityName = clazz.getSimpleName();if (entityName.endsWith("Model")) {entityName = entityName.substring(0, entityName.length() - 5);}if (entityName.endsWith("Entity")) {entityName = entityName.substring(0, entityName.length() - 6);}entityName = prefix + entityName;return entityName;}// Mybatis 查询⽅法,只需要输⼊mapper的命名空间名称和⽅法名就可以实现数据库操作/*** 执⾏删除语句* @param statement* @param parameter* @return*/public int deleteByMyBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().delete(statement, parameter);}/*** 执⾏删除语句* @param t* @param funName* @param parameter* @return*/public int deleteByMyBatis(Class<T> t, String funName, Object parameter) {String statement = t.getName() + "." + funName;return deleteByMyBatis(statement, parameter);}public int deleteByMyBatis(Class<T> t, Object parameter) {String statement = t.getName() + "." + "delete";return deleteByMyBatis(statement, parameter);}/*** 执⾏查询列表* @param statement* @param parameter* @return*/public List<T> listByMyBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().selectList(statement, parameter); }/*** 执⾏查询列表语句* @param t* @param funName* @param parameter* @return*/public List<T> listByMyBatis(Class<T> t, String funName, Object parameter) { String statement = t.getName() + "." + funName;return listByMyBatis(statement, parameter);}public List<T> ListByMyBatis(Class<T> t, Object parameter){String statement = t.getName() + "." + "select";return listByMyBatis(statement, parameter);}/*** 执⾏插⼊语句* @param statement* @param parameter* @return*/public int insertByMyBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().insert(statement, parameter);}/*** 执⾏插⼊语句* @param t* @param funName* @param parameter* @return*/public int insertByMyBatis(Class<T> t, String funName, Object parameter) {String statement = t.getName() + "." + funName;return insertByMyBatis(statement, parameter);}/*** 执⾏选择⼀条记录语句* @param statement* @param parameter* @return*/public T selectOneByMyBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().selectOne(statement, parameter); }/*** 执⾏选择⼀条记录语句* @param t* @param funName* @param parameter* @return*/public T selectOneByMyBatis(Class<T> t, String funName, Object parameter) { String statement = t.getName() + "." + funName;return selectOneByMyBatis(statement, parameter);}/*** 计数* @param t* @param parameter* @return*/public long countByMyBatis(String statement, Object parameter) {return (long)this.sqlSessionFactory.openSession().selectOne(statement, parameter); }public long countByMyBatis(Class<?> t, Object parameter){String statement = t.getName() + ".count";return countByMyBatis(statement, parameter);}/*** 更新数据* @param statement* @param parameter* @return*/public int updateByMyBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().update(statement, parameter);}/*** 更新数据* @param t* @param funName* @param parameter* @return*/public int updateByMyBatis(Class<T> t, String funName, Object parameter) {String statement = t.getName() + "." + funName;return updateByMyBatis(statement, parameter);}public int updateByMyBatis(Class<T> t, Object parameter) {String statement = t.getName() + ".update";return updateByMyBatis(statement, parameter);}/*** 插⼊数据* @param statement* @param parameter* @return*/public int insertByMayBatis(String statement, Object parameter) {return this.sqlSessionFactory.openSession().insert(statement, parameter);}public int insertByMayBatis(Class<T> t, String funName, Object parameter) {String statement = t.getName() + "." + funName;return this.sqlSessionFactory.openSession().insert(statement, parameter);}public int insertByMayBatis(Class<T> t, Object parameter) {return insertByMayBatis(t,"insert", parameter);}。

Mybatis增删改查mapper文件写法详解

Mybatis增删改查mapper文件写法详解

Mybatis增删改查mapper⽂件写法详解1. 插⼊<mapper namespace="需要实现接⼝的全类名"><insert id="需要实现的接⼝⾥的⽅法名" parameterType="⽅法参数类型,如果是对象要写全类名">INSERT sql命令(命令⾥通过#{}获取对象属性)<!--注意属性名区分⼤⼩写 --></insert><mapper>EG:<mapper namespace="com.mlj.dao.PersonDao"><insert id="insertPerson" parameterType="com.mlj.entity.Prac_Person">INSERT INTO PRAC_PERSON(p_NAME,P_PASSWORD) VALUES(#{name},#{password})</insert></mapper>2. 查询<select id="⽅法名" parameterType="⽅法参数类型" resultType="⽅法返回值类型,全类名">SELECT 表⾥字段名 AS 结果字段名 FROM 表名 WHERE 条件<!--注意:结果字段名与属性名保持⼀致,区分⼤⼩写--></select>EG:<resultMap type="Address" id="address"><result column="A_PERSON" property="personId"/><result column="A_ADDRESS" property="address"/><result column="A_NUMBER" property="number"/></resultMap><select id="selectAddressByPersonId"parameterType="ng.String" resultMap="address">SELECT * FROM PRAC_ADDRESS LEFT JOIN PRAC_PERSON ON A_PERSON=#{personId} AND PRAC_ADDRESS.A_PERSON=PRAC_PERSON.P_ID </select>此处先配置resultMapp,使表列名与属性名⼀致。

Mybatis实现数据的增删改查(CRUD)+++

Mybatis实现数据的增删改查(CRUD)+++

Mybatis实现数据的增删改查(CRUD)什么是MyBatis?MyBatis 是支持普通SQL 查询,存储过程和高级映射的优秀持久层框架。

MyBatis 消除了几乎所有的JDBC 代码和参数的手工设置以及对结果集的检索。

MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和Java 的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

MyBatis下载:https:///mybatis/mybatis-3/releasesMybatis实例对一个User表的CRUD操作:User表:-- ------------------------------ Table structure for `user`-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`userName` varchar(50) DEFAULT NULL,`userAge` int(11) DEFAULT NULL,`userAddress` varchar(200) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');在Src目录下建一个mybatis的xml配置文件Configuration.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN""/dtd/mybatis-3-config.dtd"><configuration><!-- mybatis别名定义--><typeAliases><typeAlias alias="User" type="er"/></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"/><property name="username" value="root"/><property name="password" value="admin"/></dataSource></environment></environments><!-- mybatis的mapper文件,每个xml配置文件对应一个接口--><mappers><mapper resource="com/mybatis/test/User.xml"/></mappers></configuration>定义User mappers的User.xml配置文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.mybatis.test.IUserOperation"><!-- select语句--><select id="selectUserByID" parameterType="int" resultType="User">select * from `user` where user.id = #{id}</select><!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题--><!-- <resultMap type="User" id="userResultMap"><id property="id" column="user_id" /><result property="userName" column="user_userName" /><result property="userAge" column="user_userAge" /><result property="userAddress" column="user_userAddress" /></resultMap> --><!-- 返回list的select语句,注意resultMap的值是指向前面定义好的--><!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">select * from user where erName = #{userName}</select> --><select id="selectUsersByName" parameterType="string" resultType="User">select * from user where erName = #{userName}</select><!--执行增加操作的SQL语句。

mybatis saveorupdate 自定义条件

mybatis saveorupdate 自定义条件

mybatis saveorupdate 自定义条件全文共四篇示例,供读者参考第一篇示例:MyBatis是一个非常流行的Java持久化框架,它使用简单的XML 文件或注解配置来映射Java对象和数据库表。

在使用MyBatis进行增删改查操作时,最常见的就是保存或更新数据的操作。

通常我们会使用insert和update两个SQL语句来实现保存或更新数据的功能。

但是有时候我们希望在保存或更新数据时,可以自定义一些条件来决定是执行保存操作还是更新操作。

比如我们希望在执行保存操作时,如果数据库中已经存在相同主键的数据,则执行更新操作,如果不存在则执行保存操作。

这样就可以避免出现主键冲突的情况。

在MyBatis中,可以通过自定义条件来实现这样的功能。

一般来说,在MyBatis中实现saveOrUpdate的功能有两种常见的方式:第一种方式是使用<selectKey>和<if>标签来实现。

在执行insert 操作时,使用<selectKey>标签获取数据库生成的主键值,然后通过<if>标签判断主键值是否存在,如果存在则执行更新操作,如果不存在则执行保存操作。

```xml<insert id="saveOrUpdate"parameterType="er"><selectKey keyProperty="id"resultType="ng.Long" order="BEFORE">SELECT IFNULL(MAX(id), 0) + 1 FROM user</selectKey>INSERT INTO user(id, name) VALUES (#{id}, #{name})ON DUPLICATE KEY UPDATE name = #{name}</insert>```在上面的示例中,<selectKey>标签会获取数据库中最大的主键值,并将其赋给参数对象中的id属性。

mybatis-plus的baseservice方法

mybatis-plus的baseservice方法

mybatis-plus的baseservice方法全文共四篇示例,供读者参考第一篇示例:MyBatis-Plus是一个优秀的持久层框架,它在MyBatis的基础上进行了进一步的封装和拓展,提供了更强大和便捷的数据库操作功能。

其中的BaseService方法是MyBatis-Plus中的一个重要组成部分,它提供了一系列基本的增删改查方法,可以在我们的业务代码中快速实现对数据库的操作。

BaseService提供了一系列的基本数据库操作方法,包括增删改查等功能,让我们在操作数据库时更加便捷和高效。

在使用BaseService 时,我们只需要简单地继承BaseService接口,并实现相应的方法,就可以快速实现对数据库的操作。

BaseService中的常用方法包括:1. save方法:保存数据到数据库中,可以插入一条数据或者更新一条数据,根据数据是否已经存在来决定具体操作。

2. deleteById方法:根据主键ID删除数据库中对应的数据。

5. list方法:查询数据库中符合条件的数据列表。

第二篇示例:MyBatis-Plus是MyBatis的增强工具,提供了许多便捷的功能来简化持久层开发。

BaseService是MyBatis-Plus中非常重要的一个类,它提供了一系列的通用方法,可以方便地操作数据库表中的数据。

本文将介绍BaseService的常用方法及其使用方法。

BaseService是一个抽象类,其中包含了许多CRUD(增删改查)的方法,我们可以通过继承BaseService来快速构建Service层,避免重复编写相似的代码。

下面我们来看一下BaseService中常用的方法:1. saveOrUpdate(T entity):保存或更新实体对象,根据实体对象是否有主键来判断是进行插入还是更新操作。

2. saveBatch(Collection<T> entityList):批量保存实体对象。

MyBatis-Spring(二)--SqlSessionTemplate实现增删改查

MyBatis-Spring(二)--SqlSessionTemplate实现增删改查

MyBatis-Spring(⼆)--SqlSessionTemplate实现增删改查SqlSessionTemplate是个线称安全的类,每运⾏⼀个SqlSessionTemplate时,它就会重新获取⼀个新的SqlSession,所以每个⽅法都有⼀个独⽴的SqlSession,这意味着它是线称安全的。

上⼀篇⽂章已经介绍过MyBatis-Spring项⽬的搭建过程,本节按照前⾯介绍的流程,通过SqlSessionTemplate实现数据库的增删改差。

第⼀步:创建spring-mybatis.xml⽂件并配置数据源这⾥使⽤DBCP数据库连接池的⽅式:1<!-- 第⼀步:配置数据源--使⽤数据库连接池 -->2<bean id="dataSource" class="mons.dbcp.BasicDataSource">3<property name="driverClassName" value="org.postgresql.Driver"/>4<property name="url" value="jdbc:postgresql://localhost:5433/postgres"/>5<property name="username" value="postgres"/>6<property name="password" value="postgres"/>7<!-- 最⼤数据库连接数 -->8<property name="maxActive" value="100"/>9<!-- 最⼤空闲数,即等待连接数 -->10<property name="maxIdle" value="5"/>11<!-- 最⼤等待连接时间 -->12<property name="maxWait" value="10000"/>13</bean>第⼆步:配置SqlSessionFactory1<!--第⼆步:配置SqlSessionFactory -->2<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">3<!-- 配置数据源 -->4<property name="dataSource" ref="dataSource"/>5<!-- 配置mybatis -->6<property name="configLocation" value="mybatis-config2.xml"/>7</bean>mybatis-config2.xml的配置如下:1<?xml version="1.0" encoding="UTF-8"?>2<!DOCTYPE configuration3 PUBLIC "-////DTD Config 3.0//EN"4 "/dtd/mybatis-3-config.dtd">5<!-- mybatis的基本配置⽂件:主要配置基本的上下⽂参数和运⾏环境 -->6<configuration>7<!--设置 -->8<settings>9<!--缓存配置的全局开关:如果这⾥设置成false,那么即便在映射器中配置开启也⽆济于事 -->10<setting name="cacheEnabled" value="true"/>11<!--延时加载的全局开关 -->12<setting name="lazyLoadingEnabled" value="false"/>13<!-- 是否允许单⼀语句返回多结果集 -->14<setting name="multipleResultSetsEnabled" value="false"/>15<!-- 使⽤列标签代替列名,需要兼容驱动 -->16<setting name="useColumnLabel" value="true"/>17<!-- 允许JDBC⾃动⽣成主键,需要驱动兼容。

mybatis3使用@Select等注解实现增删改查操作

mybatis3使用@Select等注解实现增删改查操作

mybatis3使⽤@Select等注解实现增删改查操作1.需要的jar包2.⽬录树3.具体代码⼀.需要的jar包第⼀个:mybatis的jar包第⼆个:mysql数据的驱动⼆.⽬录树三.具体代码使⽤框架,配置⽂件先⾏!conf.xml:(配置登录数据库,映射⽂件)<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN""/dtd/mybatis-3-config.dtd"><configuration><environments default="mysql"><environment id="mysql"><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="zhujunwen"/></dataSource></environment></environments><!-- 配置映射--><mappers><!-- 若映射⽂件mapper 是xml,则<mapper recourse...>,若映射⽂件为java⽂件,则<mapper class.....> --><mapper class="erMapper"/></mappers></configuration>映射⽂件:UserMapper.java:(⽤于映射SQL语句)package com;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;public interface UserMapper {/*这个⼀个接⼝,但不需要实现它,⽤于函数与SQL语句的映射* */@Insert("insert into tb_user(name,sex) values(#{name},#{sex})")public void insertT(User user);@Delete("delete from tb_user where id=#{id}")public void deleteById(int id);@Update("update tb_user set name=#{name},sex=#{sex} where id=#{id}")public void updateT(User user);@Select("select * from tb_user where id=#{id}")public User getUser(int id);@Select("select * from tb_user")public List<User> getAllUsers();}持久类:User.java:(持久类中的成员变量要与数据表中的字段名字⼀致)package com;public class User {private Integer id;private String name;private String sex;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String toString() {return "User [id=" + id + ", name=" + name + ", sex=" + sex + "]";}}必要变量的快速获取:(获取Session)FKSqlSessionFactory.java:package com;import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class FKSqlSessionFactory {private static SqlSessionFactory sqlSessionFactory = null;static{InputStream input;try {input = Resources.getResourceAsStream("conf.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();}public static SqlSessionFactory getSqlSessionFactory(){return sqlSessionFactory;}}测试⽂件(只是演⽰对数据库的插⼊)package com;import java.util.ArrayList;import java.util.List;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;public class Test1 {public static void main(String[] args) {SqlSessionFactory factory= FKSqlSessionFactory.getSqlSessionFactory();SqlSession session = factory.openSession();UserMapper mapper = session.getMapper(UserMapper.class);//获取映射器实例User user = new User();user.setName("zhujunwen");user.setSex("m");mapper.insertT(user); //调⽤映射器中的insertT()⽅法进⾏数据库插⼊mit();session.close();}}效果:已有数据插⼊到数据表数据表的样式:补充知识:mybatis ⼀次select操作执⾏流程分析1.测试代码package com.testmybatis;import java.io.IOException;import java.io.InputStream;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.apache.log4j.Logger;import com.alibaba.fastjson.JSON;import com.testmybatis.dao.TestMapper;import com.testmybatis.model.Test;public class testlanjie {private static Logger log=Logger.getLogger(testlanjie.class);public static void main(String args[]){List<Test> tests=null;try {String resource = "com/testmybatis/mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession();try {TestMapper mapper=session.getMapper(TestMapper.class);tests=mapper.test();mit();} finally {session.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(tests!=null)(JSON.toJSONString(tests));}}2.流程分析第⼀步构造SqlSessionFactoryString resource = "com/testmybatis/mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSessionFactoryBuilder下的build函数public SqlSessionFactory build(InputStream inputStream) {return build(inputStream, null, null);}public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {try {XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);return build(parser.parse());} catch (Exception e) {throw ExceptionFactory.wrapException("Error building SqlSession.", e);} finally {ErrorContext.instance().reset();try {inputStream.close();} catch (IOException e) {// Intentionally ignore. Prefer previous error.}}}public SqlSessionFactory build(Configuration config) {return new DefaultSqlSessionFactory(config);}先⽤配置⽂件的⽂件流对象构造⼀个XMLConfigBuilder对象,在调⽤parse函数得到Configuration对象public Configuration parse() {if (parsed) {throw new BuilderException("Each XMLConfigBuilder can only be used once.");}parsed = true;parseConfiguration(parser.evalNode("/configuration"));return configuration;}private void parseConfiguration(XNode root) {try {Properties settings = settingsAsPropertiess(root.evalNode("settings"));//issue #117 read properties firstpropertiesElement(root.evalNode("properties"));loadCustomVfs(settings);typeAliasesElement(root.evalNode("typeAliases"));pluginElement(root.evalNode("plugins"));objectFactoryElement(root.evalNode("objectFactory"));objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));reflectorFactoryElement(root.evalNode("reflectorFactory"));settingsElement(settings);// read it after objectFactory and objectWrapperFactory issue #631environmentsElement(root.evalNode("environments"));databaseIdProviderElement(root.evalNode("databaseIdProvider"));typeHandlerElement(root.evalNode("typeHandlers"));mapperElement(root.evalNode("mappers"));} catch (Exception e) {throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);}其中mybatis主要的配置都在这⾥完成,存放在configuration中,本次分析会⽤到的两个函数是environmentsElement和mapperElement,⼀个是构造datasource,⼀个是构造存放所有MapperProxyFactory的MapperRegistry,相应的源代码如下private void environmentsElement(XNode context) throws Exception {if (context != null) {if (environment == null) {environment = context.getStringAttribute("default");}for (XNode child : context.getChildren()) {String id = child.getStringAttribute("id");if (isSpecifiedEnvironment(id)) {TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));DataSource dataSource = dsFactory.getDataSource();Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory).dataSource(dataSource);configuration.setEnvironment(environmentBuilder.build());}}}}private void mapperElement(XNode parent) throws Exception {if (parent != null) {for (XNode child : parent.getChildren()) {if ("package".equals(child.getName())) {String mapperPackage = child.getStringAttribute("name");configuration.addMappers(mapperPackage);} else {String resource = child.getStringAttribute("resource");String url = child.getStringAttribute("url");String mapperClass = child.getStringAttribute("class");if (resource != null && url == null && mapperClass == null) {ErrorContext.instance().resource(resource);InputStream inputStream = Resources.getResourceAsStream(resource);XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());mapperParser.parse();} else if (resource == null && url != null && mapperClass == null) {ErrorContext.instance().resource(url);InputStream inputStream = Resources.getUrlAsStream(url);XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());mapperParser.parse();} else if (resource == null && url == null && mapperClass != null) {Class<?> mapperInterface = Resources.classForName(mapperClass);configuration.addMapper(mapperInterface);} else {throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");}}}}}其中MapperRegistry对象中存放所有MapperProxyFactory对象的容器是⼀个hashmapprivate final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();public <T> void addMapper(Class<T> type) {if (type.isInterface()) {if (hasMapper(type)) {throw new BindingException("Type " + type + " is already known to the MapperRegistry.");}boolean loadCompleted = false;try {knownMappers.put(type, new MapperProxyFactory<T>(type));// It's important that the type is added before the parser is run// otherwise the binding may automatically be attempted by the// mapper parser. If the type is already known, it won't try.MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);parser.parse();loadCompleted = true;} finally {if (!loadCompleted) {knownMappers.remove(type);}}}}在构造factory的最后返回了⼀个DefaultSqlSessionFactory对象,并将创建好的Configuration对象当作参数传给了该对象,成为了他的成员变量。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

mybatis增删改查例子一、使用MyBatis对表执行CRUD操作——基于XML的实现1、定义sql映射xml文件userMapper.xml文件的内容如下:1<?xml version="1.0" encoding="UTF-8" ?>2<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd">3<!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的4例如namespace="erMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)5-->6<mapper namespace="erMapper">7<!-- 在select标签中编写查询的SQL语句,设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复8使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型9resultType="er"就表示将查询结果封装成一个User类的对象返回10User类就是users表所对应的实体类11-->12<!--13根据id查询得到一个user对象14-->15<select id="getUser" parameterType="int"16resultType="er">17select * from users where id=#{id}18</select>1920<!-- 创建用户(Create) -->21<insert id="addUser" parameterType="er">22insert into users(name,age) values(#{name},#{age})23</insert>2425<!-- 删除用户(Remove) -->26<delete id="deleteUser" parameterType="int">27delete from users where id=#{id}28</delete>2930<!-- 修改用户(Update) -->31<update id="updateUser" parameterType="er">32update users set name=#{name},age=#{age} where id=#{id}33</update>3435<!-- 查询全部用户-->36<select id="getAllUsers" resultType="er">37select * from users38</select>3940</mapper>单元测试类代码如下:1package me.gacl.test;23import java.util.List;4import er;5import me.gacl.util.MyBatisUtil;6import org.apache.ibatis.session.SqlSession;7import org.junit.Test;89public class TestCRUDByXmlMapper {1011@Test12public void testAdd(){13//SqlSession sqlSession = MyBatisUtil.getSqlSession(false);14SqlSession sqlSession = MyBatisUtil.getSqlSession(true);15/**16* 映射sql的标识字符串,17* erMapper是userMapper.xml文件中mapper标签的namespace属性的值,18* addUser是insert标签的id属性值,通过insert标签的id属性值就可以找到要执行的SQL19*/20String statement = "erMapper.addUser";//映射sql的标识字符串21User user = new User();22user.setName("用户孤傲苍狼");23user.setAge(20);24//执行插入操作25int retResult = sqlSession.insert(statement,user);26//手动提交事务27//mit();28//使用SqlSession执行完SQL之后需要关闭SqlSession29sqlSession.close();30System.out.println(retResult);31}3233@Test34public void testUpdate(){35SqlSession sqlSession = MyBatisUtil.getSqlSession(true);36/**37* 映射sql的标识字符串,38* erMapper是userMapper.xml文件中mapper标签的namespace属性的值,39* updateUser是update标签的id属性值,通过update标签的id属性值就可以找到要执行的SQL 40*/41String statement = "erMapper.updateUser";//映射sql的标识字符串42User user = new User();43user.setId(3);44user.setName("孤傲苍狼");45user.setAge(25);46//执行修改操作47int retResult = sqlSession.update(statement,user);48//使用SqlSession执行完SQL之后需要关闭SqlSession49sqlSession.close();50System.out.println(retResult);51}5253@Test54public void testDelete(){55SqlSession sqlSession = MyBatisUtil.getSqlSession(true);56/**57* 映射sql的标识字符串,58* erMapper是userMapper.xml文件中mapper标签的namespace属性的值,59* deleteUser是delete标签的id属性值,通过delete标签的id属性值就可以找到要执行的SQL60*/61String statement = "erMapper.deleteUser";//映射sql的标识字符串62//执行删除操作63int retResult = sqlSession.delete(statement,5);64//使用SqlSession执行完SQL之后需要关闭SqlSession65sqlSession.close();66System.out.println(retResult);67}6869@Test70public void testGetAll(){71SqlSession sqlSession = MyBatisUtil.getSqlSession();72/**73* 映射sql的标识字符串,74* erMapper是userMapper.xml文件中mapper标签的namespace属性的值,75* getAllUsers是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL76*/77String statement = "erMapper.getAllUsers";//映射sql的标识字符串78//执行查询操作,将查询结果自动封装成List<User>返回79List<User> lstUsers = sqlSession.selectList(statement);80//使用SqlSession执行完SQL之后需要关闭SqlSession81sqlSession.close();82System.out.println(lstUsers);83}84 }二、使用MyBatis对表执行CRUD操作——基于注解的实现1、定义sql映射的接口UserMapperI接口的代码如下:1package me.gacl.mapping;23import java.util.List;4import er;5import org.apache.ibatis.annotations.Delete;6import org.apache.ibatis.annotations.Insert;7import org.apache.ibatis.annotations.Select;8import org.apache.ibatis.annotations.Update;910/**11* @author gacl12* 定义sql映射的接口,使用注解指明方法要执行的SQL13*/14public interface UserMapperI {1516//使用@Insert注解指明add方法要执行的SQL17@Insert("insert into users(name, age) values(#{name}, #{age})")18public int add(User user);1920//使用@Delete注解指明deleteById方法要执行的SQL21@Delete("delete from users where id=#{id}")22public int deleteById(int id);2324//使用@Update注解指明update方法要执行的SQL25@Update("update users set name=#{name},age=#{age} where id=#{id}")26public int update(User user);2728//使用@Select注解指明getById方法要执行的SQL29@Select("select * from users where id=#{id}")30public User getById(int id);3132//使用@Select注解指明getAll方法要执行的SQL33@Select("select * from users")34public List<User> getAll();35 }需要说明的是,我们不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可。

相关文档
最新文档