0

I want to insert two rows into master and detail table.

Master and detail table with autoincremented 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)
);

Model classes are:

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;
}

There is example from Hibernate:

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

I try to insert with 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();

How to get id_user and insert row into detail table?

Vadim
  • 557
  • 8
  • 21

1 Answers1

0

I think you can use ps.getGeneratedKeys() method and send Statement.RETURN_GENERATED_KEYS as second parameter in conn.prepareStatement() method.

alayor
  • 4,537
  • 6
  • 27
  • 47
  • Also the linked question doesn't answer it for Oracle, because there are some extra gotcha's when doing this on Oracle, see for example http://stackoverflow.com/questions/24136223/java-jdbc-primary-key-oracle-database – Mark Rotteveel Jan 06 '17 at 15:09
  • 1
    Your current answer is slightly better, but not actually correct for Oracle, see the link in my previous comment. – Mark Rotteveel Jan 06 '17 at 15:14