插入数据的时候,往往需要获取主键值.但是有时候主键是自增长的那么,就不太适用手动添加主键值了,此时需要一种可以回显主键参数的方法, 下面以jdbc.mybatis的实现举例 此时使用的是jdbc的话或许能简单?too young too simple ! package hellxz; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.…
 useGeneratedKeys="true" keyProperty="id" <insert id="insertReturnPrimaryKey" parameterType="com.haitao55.spider.order.robot.platform.dos.TaskHistoryDO" useGeneratedKeys="true" keyProperty="id"…
代码如下: @Override public void saveTopicResource(TopicResourceModel model, Integer userId) { TopicResource topicResource = new TopicResource(); BeanUtils.copyProperties(model, topicResource); int result=0; if (model.getResId() == null) { topicResource.s…
mybatis插入数据后获取自增主键 首先理解这就话的意思:就是在往数据库表中插入一条数据的同时,返回该条数据在数据库表中的自增主键值. 有什么用呢,举个例子: 你编辑一条新闻,同时需要给该新闻打上标签(可以一个或者多个:比如:女性,爱,钱等等),然后存储到数据库中.怎么存,肯定涉及到三张表,新闻表,标签表,新闻标签id关联表 新闻表插入数据简单,标签表插入数据简单.那新闻标签表呢,如何关联,那是不是需要新闻表和标签表插入数据的时候,返回它们的主键Id然后再存储到新闻标签表中. 这种场景还是蛮常…
向数据库中插入数据时,大多数情况都会使用自增列或者UUID做为主键.主键的值都是插入之前无法知道的,但很多情况下我们在插入数据后需要使用刚刚插入数据的主键,比如向两张关联表A.B中插入数据(A的主键是B的外键),向A表中插入数据之后,向B表中插入数据时需要用到A的主键. 比如添加一个用户,同时返回插入用户后得到的用户id: /** * 添加用户信息 * @param user * @throws Exception */ public int insertUser(User user) thro…
方法有很多,参考 mysql函数之六:mysql插入数据后返回自增ID的方法,last_insert_id(),selectkey 这里记录一下工作中自己用到的selectkey方法的详细过程. pojo类: public class Client { /** * 客户id */ @Id private Integer id; /** * 客户名称 */ private String name; //其他的一些域自己补充,对应get/set方法也要添加 /** * 获取客户id * * @ret…
<insert id="insert" parameterType="com.pojo.TSubject" useGeneratedKeys="true" keyProperty="subjectid" > insert into t_subject ( parentid, subjectname, subjecttype, subjectitem, subjectanser, displaytype) value…
有时候使用mybatis插入数据后,需要用到记录在数据库中的自增id,可以利用keyProperty来返回,赋值给实体类中的指定字段. 单条记录插入并返回 First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the keyProperty to the…
需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值. 方法:在mapper中指定keyProperty属性,示例如下: <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User"> insert into us…
1.Java代码: 1.1 entity类: User.java public class User { private int userId; private String userName; private String password; private String comment; //这里要添加 setter and getter  略 } 1.2 DAO类: UserDao.java public interface UserDao { public int insertAndGe…