mybatis主键生成策略注解,mybatis获取insert的主键
目录
用注解实现框架插入数据返回自增的主键身份设计数据库表设计爪哇组件对象添加制图人接口框架注解增(返回自增id)删查改以及(一对一,一对多,多对多)数据库表目录结构导入坐标(包)配置文件实体类制图人接口编写测试
用注解实现Mybatis插入数据返回自增的主键Id
我们在数据库表设计的时候,一般都会在表中设计一个自增的编号作为表的主键。这个编号也会关联到其它表的外键。
这就要求往表中插入数据时能返回表的自增id,用这个身份去给关联表的字段赋值。下面讲一下如何通过注解的方式实现插入数据时返回自增身份证.
设计数据库表
创建表` TBL _用户`(` id ` int(11)NOT NULL AUTO _ INCREMENT,` name ` varchar(255)NOT NULL DEFAULT ,` age` int(4) NOT NULL DEFAULT 0 ,主键(` id `))ENGINE=InnoDB AUTO _ INCREMENT=8 DEFAULT CHARSET=utf8;
设计Java bean对象
公共类用户{ private int userId=-1;私有字符串名称="";private int age=-1;@将公共字符串重写为String(){ return name : name age : age;} public int get userId(){ return userId;} public void set userId(int userId){ this。userId=userId} public String getName(){ return name;} public void set name(String name){ this。name=名称;} public int getAge(){ return age;} public void setAge(int age){ this。年龄=年龄;}}
添加mapper接口
@ mapper公共接口用户映射程序{ @ Insert( Insert into TBL _用户(姓名,年龄)值(# {姓名},# {年龄})@ Options(useGeneratedKeys=true,keyProperty=用户标识,键列=标识)void Insert User(用户用户);} 通过以上几个步骤就可以实现在插入用户到数据库时返回自增身份证.数据插入成功后,id值被反填到用户对象中,调用getUserId()就可以获取。
上面的写法有个地方需要注意一下:如果插入用户使用了@Param注解,如:void insertUser(@ Param(" User ")User User),keyProperty需要指定为用户标识.
Mybatis注解增(返回自增id) 删查改以及(一对一,一对多,多对多)
数据库表
目录结构
导入坐标(包)
依赖关系依赖关系组id MySQL/组id artifactId MySQL-连接器-java/artifactId版本5 .1 .32/版本/依赖关系依赖关系大型旅行车的
; <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> </dependencies>
配置文件
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/springbootjdbc.username=rootjdbc.password=111111
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <properties resource="jdbc.properties"/><!-- 别名--> <typeAliases> <package name="com.zyw.domain"/> </typeAliases> <!-- 注册自定义类型处理器--> <typeHandlers> <typeHandler handler="com.zyw.typeHandler.TypeHandler"/> </typeHandlers> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <package name="com.zyw.mapper"/> </mappers></configuration>
log4j.properties
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c:/mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change info to debug ###log4j.rootLogger=debug, stdout
实体类
Order
package com.zyw.domain;public class Order { private Integer id; private String ordername; private Integer ordernum; private User user; @Override public String toString() { return "Order{" + "id=" + id + ", ordername=" + ordername + + ", ordernum=" + ordernum + ", user=" + user + }; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOrdername() { return ordername; } public void setOrdername(String ordername) { this.ordername = ordername; } public Integer getOrdernum() { return ordernum; } public void setOrdernum(Integer ordernum) { this.ordernum = ordernum; } public User getUser() { return user; } public void setUser(User user) { this.user = user; }}
Role
package com.zyw.domain;import java.util.List;public class Role { private Integer id; private String roleName; private String roleDesc; private List<User> userList; public void setUser(List<User> userList) { this.userList = userList; } public List<User> getUser() { return userList; } @Override public String toString() { return "Role{" + "id=" + id + ", roleName=" + roleName + + ", roleDesc=" + roleDesc + + ", user=" + userList + }; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; }}
User
package com.zyw.domain;import java.util.Date;import java.util.List;public class User { private Integer id; private String username; private String email; private String password; private Long phoneNum; private Date birthday; private List<Order> orderList; public List<Order> getOrderList() { return orderList; } public void setOrderList(List<Order> orderList) { this.orderList = orderList; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setPhoneNum(Long phoneNum) { this.phoneNum = phoneNum; } public Long getPhoneNum() { return phoneNum; } @Override public String toString() { return "User{" + "id=" + id + ", username=" + username + + ", email=" + email + + ", password=" + password + + ", phoneNum=" + phoneNum + ", birthday=" + birthday + ", orderList=" + orderList + }; }}
mapper接口编写
OrderMapper
public interface OrderMapper { @Select("select * from orders ") @Results({ @Result(column = "id",property = "id"), @Result(column = "ordername",property = "ordername"), @Result(column = "ordernum",property = "ordernum"), @Result( property = "user", column = "uid", javaType = User.class, one = @One(select = "com.zyw.mapper.UserMapper.findById") ) }) public List<Order> findAll(); @Select("select * from orders where uid=#{uid}") public List<Order> findByUid(Integer uid);}
RoleMapper
public interface RoleMapper { @Select("select * from sys_role") @Results({ @Result(column = "id",property = "id"), @Result(column = "roleName",property = "roleName"), @Result(column = "roleDesc",property = "roleDesc"), @Result( property = "userList", column = "id", javaType = List.class, many = @Many(select = "com.zyw.mapper.UserMapper.findUserAndRoleById") ) }) public List<Role> findRoleAndUser();}
UserMapper (注意自增id是返回到实体类)
public interface UserMapper { @Select("select * from sys_user") public List<User> findAll(); @Select("select * from sys_user where id=#{id}") public User findById(Integer id); @Insert("insert into sys_user values(#{id},#{username},#{email},#{password},#{phoneNum},#{birthday})") @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") public void insertUser(User user); @Update("update sys_user set password=#{password} where id=#{id}") public void updateUser(User user); @Delete("delete from sys_user where id=#{id}") public void deleteUser(Integer id); @Select("select * from sys_user") @Results({ @Result(column = "id",property = "id"), @Result(column = "username",property = "username"), @Result(column = "password",property = "password"), @Result(column = "email",property = "email"), @Result(column = "phoneNum",property = "phoneNum"), @Result(column = "birthday",property = "birthday"), @Result( property = "orderList", //封装的属性名称 column = "id", //根据哪个字段去查询order表中的数据 javaType = List.class, //返回类型 many = @Many(select = "com.zyw.mapper.OrderMapper.findByUid") ) }) public List<User> findUserAndOrder(); @Select("select * from sys_user u,sys_user_role ur where u.id=ur.userId and ur.roleId=#{id}") public List<User> findUserAndRoleById(Integer id);}
测试
单表增删查改
AnnoTest
public class AnnoTest { private UserMapper mapper ; @Before public void before() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = build.openSession(true); mapper=sqlSession.getMapper(UserMapper.class); } @Test public void testFindAll(){ List<User> userList = mapper.findAll(); for (User user : userList) { System.out.println(user); } } @Test public void testFindById(){ User byId = mapper.findById(1); System.out.println(byId); } @Test public void testInsertUser(){ User user=new User(); user.setUsername("小张"); user.setPassword("951753"); user.setPhoneNum(13449484984L); user.setEmail("951@qq.com"); user.setBirthday(new Date()); mapper.insertUser(user);System.out.println(user.getId()); } @Test public void testUpdateUser(){ User user=new User(); user.setId(1); user.setPassword("123456"); mapper.updateUser(user); } @Test public void testDeleteUser(){ mapper.deleteUser(9); }
一对一
AnnoTestOneToOne
public class AnnoTestOneToOne { private OrderMapper mapper ; @Before public void before() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = build.openSession(true); mapper=sqlSession.getMapper(OrderMapper.class); } @Test public void testDemo(){ List<Order> orderList = mapper.findAll(); for (Order order : orderList) { System.out.println(order); } }}
一对多
AnnoTestOneToMany
public class AnnoTestOneToMany { private UserMapper mapper ; @Before public void before() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = build.openSession(true); mapper=sqlSession.getMapper(UserMapper.class); } @Test public void testDemo(){ List<User> userList = mapper.findUserAndOrder(); for (User user : userList) { System.out.println(user); } }}
多对多
AnnoTestManyToMany
public class AnnoTestManyToMany { private RoleMapper mapper ; @Before public void before() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = build.openSession(true); mapper=sqlSession.getMapper(RoleMapper.class); } @Test public void testDemo(){ List<Role> roleList = mapper.findRoleAndUser(); for (Role role : roleList) { System.out.println(role); } }}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。