Pass FK field from SQL Server to Java object class - java

My application uses data from a jsp form to populate the tables in the SQL Server and create the objects in java. All ids (PK) in the tables are defined as autoincrement. However, I don't know how to insert the FKs data in the tables and add it to the java objects. For example, I have the table Instructor that has FK_course and FK_department.
CREATE TABLE [dbo].[instructors](
[instructor_id] [int] IDENTITY(1,1) NOT NULL,
[instructor_lastname] [nvarchar](250) NULL,
[instructor_firstname] [nvarchar](250) NULL,
[department_id] [int] NULL,
[course_id] [int] NULL,
CONSTRAINT [PK_instructors] PRIMARY KEY CLUSTERED
ALTER TABLE [dbo].[instructors] WITH CHECK ADD CONSTRAINT [FK_course_instructor] FOREIGN KEY([course_id])
REFERENCES [dbo].[courses] ([course_id])
GO
ALTER TABLE [dbo].[instructors] WITH CHECK ADD CONSTRAINT [FK_department_instructor] FOREIGN KEY([department_id])
REFERENCES [dbo].[departments] ([department_id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
In my code a have the class Instructor that has the gets and sets, and I use doPost to insert the data and create the object in java.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//insert instructor
String lastname = request.getParameter("lname");
String firstname = request.getParameter("fname");
// int departament_id = ??
// String course_id= ???
Instructor instructor = new Instructor(lastname, firstname);//departament_id? course_id?
formService.insertInstructor(instructor);
In another file I do all the DB connection to insert the data in the database. But the problem is with department_id and course_id. How can I get the data from the tables Course and Department to insert in the table instructors? Here is my code for Instructor table, but is missing those two fields that I do know how to insert in the table and add to the object in java. I appreacite your time and help.
public void insertInstructor(Instructor instructor) {
Connection connection = Database.getConnection();
String sql = "INSERT INTO My_app.dbo.instructors(instructor_lastname, instructor_firstname) VALUES (?,?);";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, instructor.getLastname());
statement.setString(2, instructor.getFirstname());
// statement.setInt(3, instructor.getDepartment_id());
// statement.setString(3, instructor.getCourse());
statement.execute();
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

Related

Adding List<Object> as a variable to database using JDBC

So I'm trying to add to database using JDBC with HSQLDB from files. And I need to insert the List<Object> as a variable into the database.
This is what it looks like as a Java object:
public class Plant {
private Long id;
private String plantName;
private List<PlantParts> plantParts;
...
}
public class PlantParts {
private String leaves;
private String pedicle;
private String petals;
...
}
In folder resources I have a file called insert_plant.sql that contains this query:
INSERT INTO PLANTS (id, plantname, plantparts)
VALUES (NEXT VALUE FOR sequence, ?, ?);
And the table is generated with this:
CREATE SEQUENCE sequence START WITH 1;
CREATE TABLE PLANTS (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
plantparts VARCHAR(255) NULL, //No idea what to put here
);
And now in Java I am calling this:
public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname, List<PlantParts> plantparts) throws SQLException{
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = basicDataSource.getConnection();
stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"), new String[]{"id"});
stmt.setString(1, plantname);
stmt.setString(2, plantparts); //And no idea what to do here
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
The requests will usually come as a JSON:
{ "id": 5,
"plantName": "awesome plant",
"plantParts":[
{"leaves":"green","pedicle":"yellow","petals":"many"},
{"leaves":"red","pedicle":"yellow","petals":"few"}
]
}
My guess is that they should be held in the separate tables, but how can I do that and when I would need to get the object then how could I get it as a whole.
The SQL model of your data will be different from Java in how the Plant and PlantParts objects are linked together. In the Java model, Plant has a collection of PlantParts objects. In the SQL model, the PlantParts objects reference the Plant object.
So you need these two tables:
CREATE TABLE plants (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
);
CREATE TABLE plantparts (
id BIGINT NOT NULL PRIMARY KEY,
leaves VARCHAR(255) NOT NULL,
pedicles VARCHAR(255) NOT NULL,
petals VARCHAR(255) NOT NULL,
plantid BIGINT NOT NULL,
FOREIGN KEY (plantid) REFERENCES plants(id)
);
Note there is no column in the plants table for the PlantParts objects. The data for the PlantParts in your JSON object goes into two rows of the plantparts table. The plantid column of both of these rows will contain the id of the Plant object, which is 5.

Java JDBC adding automatic value to database

I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.

H2 DB: How to check whether table schema is initialized programmatically?

I have a DB schema that creates several tables and fills them with data. I want to check whether db contains corresponding tables or not during app start. I could check for db file existence, but H2 creates db if it doesn't exist. So the only way, I think, is to check for tables existence.
Here is the code of how I initialize DB:
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS table1 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS table2 (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(100), record INT, record_date DATE, UNIQUE(name))");
st.execute("CREATE TABLE IF NOT EXISTS daily_record_stat (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, date DATE, table1_id INT, table1_record INT, table2_id INT," +
" table2_record INT, total_record INT);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table1_id) REFERENCES table1(id);");
st.execute("ALTER TABLE daily_record_stat ADD FOREIGN KEY (table2_id) REFERENCES table2(id);");
st.execute("INSERT INTO table1 VALUES(1, 'non_existed_stub', 0, NULL)");
st.execute("INSERT INTO table2 VALUES(1, 'non_existed_stub', 0, NULL)");
conn.close();
As you see, I check for table existence before creation using IF NOT EXISTS statement. But then I run at the problem with ALTER and INSERT - these commands don's allow IF usage.
I tried to do the following:
Connection conn = DriverManager.getConnection("jdbc:h2:database/svc", "sa", "");
ResultSet meta = conn.getMetaData().getTables(null, null, "table1", null);
if(meta.next()) {
//do something
}
But meta.next() is false.
So how to check whether table schema is initialized? Or maybe this should be done some other way?
Not sure if that's what you mean by saying to check programmatically, buy you can try to use DatabaseMetaData.getTables(). This call will return ResultSet which you'll have to check programmatically. You can see what fields are returned in this ResultSet in corresponding section here. And meta data itself can be obtained by conn.getMetaData().
Following code should return all tables which names start with 'TABLE':
ResultSet meta = conn.getMetaData().getTables(null, null, "TABLE%", new String[]{"TABLE"});
while (meta.next()) {
System.out.println(meta.getString(3));
}
Note that you have to specify table name pattern in upper case. Also it's good to pass table types that you need, although it is optional.
This is a check I used to (re)create the H2 database:
// IMPORTANT A sorted list of table names.
private static final String[] REQUIRED_TABLES = { "USER", ... };
public static final String CREATE_USER = "create table USER (...)";
private boolean schemaExists() throws SQLException {
final List<String> requiredTables = Arrays.asList(REQUIRED_TABLES);
final List<String> tableNames = new ArrayList<String>();
final Connection conn = dataSource.getConnection();
try {
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
rs.close();
st.close();
}
finally {
if (conn != null) { conn.close(); }
}
Collections.sort(tableNames);
return tableNames.equals(requiredTables);
}
private void initializeDatabase() throws SQLException {
final Connection conn = dataSource.getConnection();
try {
if (schemaExists()) {
return;
}
final Statement st = conn.createStatement();
st.executeUpdate(CREATE_USER);
conn.commit();
}
finally {
if (conn != null) { conn.close(); }
}
}
And you just call:
initializeDatabase();
Notice the list of required tables has to be sorted because I use List.equals() to compare two lists. It would probably be better to also programmatically sort the required tables list too.
It's not fool-proof (not checking if any table exists and if it should be altered) but it works for me.
Take a look at the SHOW command for other uses.

How to run mysql insert without duplicates in java

I have a method which insert a record to mysql database as bellow,
public boolean addOrganization(OrganizationDTO organizationDTO) {
Connection con = null;
try {
String insertOrganizationSQL = "INSERT INTO organizations (org_id, org_name) VALUES(?, ?)";
con = JDBCConnectionPool.getInstance().checkOut();
PreparedStatement insertOrgPS = (PreparedStatement) con.prepareStatement(insertOrganizationSQL);
insertOrgPS.setString(1, organizationDTO.getOrg_id());
insertOrgPS.execute();
return true;
} catch (Exception e) {
JDBCConnectionPool.getInstance().checkIn(con);
logger.error(e.getLocalizedMessage());
e.printStackTrace();
return false;
} finally {
JDBCConnectionPool.getInstance().checkIn(con);
}
}
database table,
CREATE TABLE `organizations` (
`org_id` varchar(5) NOT NULL,
`org_name` varchar(100) DEFAULT NULL,
`sys_dat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user` varchar(100) NOT NULL,
PRIMARY KEY (`org_id`)
)
what I need is, when I insert a new record if, that is a duplicate exit the method without trying to insert and inform the user that it is a duplicate record. Is it possible to do without writing another method to search the record before inserting?
I would add a UNIQUE constraint to your table. For example, if org_name needs to be unique:
ALTER TABLE organizations ADD UNIQUE (org_name);
Then observe what's returned when you try to insert a duplicate record through Java. Add code to check for this, and if it occurs, display the message to your user.
Here is the reference documentation for ALTER TABLE.
Thats right, Alter table will surely help.
In your case, let say, both org_id and org_name is there, I would add unique in both, just avoid any confusion later.

JDBC: foreign key on PK created in same transaction

I have two tables in my MySQL database, which were created like this:
CREATE TABLE table1 (
id int auto_increment,
name varchar(10),
primary key(id)
) engine=innodb
and
CREATE TABLE table2 (
id_fk int,
stuff varchar(30),
CONSTRAINT fk_id FOREIGN KEY(id_fk) REFERENCES table1(id) ON DELETE CASCADE
) engine=innodb
(These are not the original tables. The point is that table2 has a foreign key referencing the primary key in table 1)
Now in my code, I would like to add entries to both of the tables within one transaction. So I set autoCommit to false:
Connection c = null;
PreparedStatement insertTable1 = null;
PreparedStatement insertTable2 = null;
try {
// dataSource was retreived via JNDI
c = dataSource.getConnection();
c.setAutoCommit(false);
// will return the created primary key
insertTable1 = c.prepareStatement("INSERT INTO table1(name) VALUES(?)",Statement.RETURN_GENERATED_KEYS);
insertTable2 = c.prepareStatement("INSERT INTO table2 VALUES(?,?)");
insertTable1.setString(1,"hage");
int hageId = insertTable1.executeUpdate();
insertTable2.setInt(1,hageId);
insertTable2.setString(2,"bla bla bla");
insertTable2.executeUpdate();
// commit
c.commit();
} catch(SQLException e) {
c.rollback();
} finally {
// close stuff
}
When I execute the code above, I get an Exception:
MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
It seems like the primary key is not available in the transaction before I commit.
Am I missing something here? I really think the generated primary key should be available in the transaction.
The program runs on a Glassfish 3.0.1 using mysql-connector 5.1.14 and MySQL 5.5.8
Any help is really appreciated!
Regards,
hage
You missed something for the returned updated id , you have to do like this :
Long hageId = null;
try {
result = insertTable1.executeUpdate();
} catch (Throwable e) {
...
}
ResultSet rs = null;
try {
rs = insertTable1.getGeneratedKeys();
if (rs.next()) {
hageId = rs.getLong(1);
}
...
Instead of using executeUpdate() use execute() and then return the primary key.
http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate
But I don't work with db...so I could do a mistake

Categories

Resources