External serial key is self-generated when inserting

0

I have a table "clients" :

CREATE TABLE clients
(
  id serial NOT NULL,
  name character(25),
  user_id serial NOT NULL,
  CONSTRAINT "Client_pkey" PRIMARY KEY (id),
  CONSTRAINT clients_id_key UNIQUE (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE clients
  OWNER TO postgres;

Another table "users" :

    CREATE TABLE users
    (
      id serial NOT NULL,
      name character(20),
      surname character(20),
      password character(15),
      admin boolean,
      CONSTRAINT users_pkey PRIMARY KEY (id),
      CONSTRAINT users_id_key UNIQUE (id)
    )
    WITH (
      OIDS=FALSE
    );
    ALTER TABLE users
      OWNER TO postgres;

The problem is this:

When I do a Insert (id, name) in the clients (without user_id) table, the user_id column is self-generated a value automatically, which I do not want to happen, I want user_id to stay in null / worthless , and only insert id and name.

Method to do the Insert :

private final Connection conn = ConnectToDatabase.createConnection();
    private final String SQL_CREATE_CLIENT = "INSERT INTO clients (id, name) VALUES (?, ?)";

public void createClient(Client client) {
        try (PreparedStatement pstmt = conn.prepareStatement(SQL_CREATE_CLIENT, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, client.getId());
            pstmt.setString(2, client.getName());
            pstmt.executeUpdate();
            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    client.setId(generatedKeys.getInt(1));
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

The relationship between the 2 tables is this:

  • A user has many clients.
  • A client has only one user.
  • asked by Bryan Romero 28.11.2018 в 17:21
    source

    0 answers