如何在JDBC中获取id_user(主键())

时间:2017-01-06 14:54:38

标签: java oracle hibernate jdbc

我想在master和detail表中插入两行。

带有自动增量ID的主表和详细信息表。

CREATE TABLE MI_User (
    id_user NUMBER(11) NOT NULL,
    age NUMBER(3),
    name_user varchar2(128),
    constraint USER_PK PRIMARY KEY (id_user));

CREATE TABLE Friends (
    id_friend NUMBER(11) not null,
    name VARCHAR2(64),
        id_user NUMBER(11) NOT NULL,
    constraint FRIEND_PK PRIMARY KEY (id_friend)
);

模型类是:

public class User {
    private String id;
    private Integer age;
    private String name;
    private ArrayList<Friend> friends;
}

public class Friend {
    private Long id_user;
    private String name;
}

来自Hibernate的例子:

tx = session.beginTransaction();
User user = new User(name, age);
employeeID = (Integer) session.save(employee); 
tx.commit();

我尝试使用JDBS插入:

conn = DriverManager
                    .getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
            ps = conn
                    .prepareStatement("INSERT INTO MI_USER (BALANCE, AGE, NAME_USER, GENDER, COMPANY, EMAIL, ADDRESS)\n" +
                            "    VALUES (?, ?, ?, ?, ?, ?, ?)");
            ps.setDouble(1, user.getDoubleBallans());
            ps.setInt(2, user.getAge());
            ps.setString(3, user.getName());
            ps.executeUpdate();

如何获取id_user并将行插入详细信息表?

1 个答案:

答案 0 :(得分:0)

我认为您可以使用ps.getGeneratedKeys()方法并在Statement.RETURN_GENERATED_KEYS方法中将conn.prepareStatement()作为第二个参数发送。