jdbc、Mybatis插入数据主键回显的实现方法

插入数据的时候,往往需要获取主键值。但是有时候主键是自增长的那么,就不太适用手动添加主键值了,此时需要一种可以回显主键参数的方法,

下面以jdbc、mybatis的实现举例

此时使用的是jdbc的话或许能简单?too young too simple !

 1 package hellxz;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 
10 public class Jdbc {
11     public static void main(String[] args) {
12         Connection conn = null;
13         PreparedStatement pstmt = null;
14         ResultSet rsKey = null;
15         try {
16             Class.forName("com.mysql.jdbc.Driver");
17             //使用&是为了避免框架中可能遇到的bug,养成好习惯
18             String url = "jdbc:mysql://localhost/article?characterEncoding=utf8&useSSL=false";
19             //获取连接
20             conn = DriverManager.getConnection(url,"root","root");
21             // 更改自动提交为false,保证事务完整性:要么全完成,要么全失败
22             conn.setAutoCommit(false);
23             String sql = "insert into article vaules(null,?)"; // 主键id自增可以插null
24             pstmt.setString(2, "name");
25             pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
26             rsKey = pstmt.getGeneratedKeys(); // 获取插入的主键值结果集
27             rsKey.next(); 
28             int rootId = rsKey.getInt(1); //拿到主键值
29             //打印看看
30             System.out.println(rootId);
31             pstmt.executeUpdate();
32             conn.commit();
33         } catch (Exception e) {
34             //捕获异常回滚数据
35             try {
36                 conn.rollback();
37             } catch (SQLException e2) {
38                 e2.printStackTrace();
39             }
40             e.printStackTrace();
41         } finally {
42             try {
43                 //开启自动提交
44                 conn.setAutoCommit(true);
45                 //关闭连接
46                 if (rsKey != null) {
47                     rsKey.close();
48                     rsKey = null;
49                 }
50                 if(pstmt != null){
51                     pstmt.close();
52                     pstmt = null;
53                 }
54                 if (conn != null) {
55                     conn.close();
56                     conn = null;
57                 }
58             } catch (SQLException e3) {
59                 e3.printStackTrace();
60             }
61         }
62     }
63 }

那我们接下来看看mybatis,mybatis的配置文件这里就不多说了,我们需要改的只有一个地方:xxxMapper.xml (其中xxx代表你用到的mapper),但有两种修改方法

具体实现如下:

方法一: 使用useGeneratedKeys

1 <insert id="insert" parameterType="com.taotao.pojo.TbContentCategory" useGeneratedKeys="true" keyProperty="id">
2     insert into tb_content_category (id, parent_id, name, 
3       status, sort_order, is_parent, 
4       created, updated)
5     values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, 
6       #{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT}, 
7       #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
8 </insert>

方法二:在mapper.xml中加入一条同事务的查询语句:select last_insert_id;

 1 <insert id="insert" parameterType="com.taotao.pojo.TbContentCategory" >
 2       <!-- keyProperty:主键pojo的名字,returnType:使用的是mybatis对java.lang.Long类型的别称
 3               order:对应的是这条语句是在插入前查询还是之后 -->
 4       <selectkey keyProperty="id" returnType="long" order="AFTER">
 5           SELECT LAST_INSERT_ID
 6       </selectKey>
 7     insert into tb_content_category (id, parent_id, name, 
 8       status, sort_order, is_parent, 
 9       created, updated)
10     values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, 
11       #{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT}, 
12       #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
13 </insert>

这样我们在程序里就可以插入完成后就直接取主键id就可以了

 参考转载请写明出处:http://www.cnblogs.com/hellxz/p/mybatis_studynote.html

原文地址:https://www.cnblogs.com/hellxz/p/mybatis_studynote.html