solution with JAVA or Postgres for insertion in database - java

(source: hostingpics.net)
how can I add a new customer or supplier?, last time I was using this class for one table "customer":
Code:
public int addnewcustomer(){
int idcust;
DBConnection eConnexion = new DBConnection();
try {
//Statement state = eConnexion.getConnexion().createStatement();
String sql = "INSERT INTO customer(name_cust, num_cust, adress_cust, city_cust , tel_cust, ref_cust)";
sql+= "VALUES (?,?,?,?,?,?)";
PreparedStatement insertQuery = eConnexion.getConnexion().prepareStatement(sql);
insertQuery.setString(1,Name_cust);
insertQuery.setString(2,Num_cust);
insertQuery.setString(3,Adress_cust);
insertQuery.setString(4,City_cust );
insertQuery.setString(5,Tel_cust);
insertQuery.setString(6,Ref_cust);
insertQuery.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null,"Erreur:the addition is not performed with Succee!");
idcust = 0;
}
eConnexion.closeConnection();
idcust= Services.getLastInsertedId("customer","id_customer");
return idcust;
}
Currently, I attach all tables with new table "person". All tables now extend "person", I tried to add new customer with super variables "person" but I'm stuck in filling foreign key "id_pers FK".

First you need to persist a person into your database. After a successful(!) persist, you can query for the id the database used to insert the data. Most databases also provide a method to directly retrieve the used id after an insert.
After you have successfully persisted the person you can use the id for the foreign key column.
You may consider using a transaction for these actions, as there should never be a person persisted without a customer/employee whatever extending the persons data.
With a transaction, you can rollback the previous actions, for example if something goes wrong during the insertion of the customer.

Related

Can't delete row from a database

I'm working at some school project and my job here is to make a delete button for that list view in Java FX, but the problem is that when i want to proceed that it shows me this error. I tried some solutions, but none of them worked.
so here's the code
#FXML
private void removeStudentOnClick(ActionEvent event) throws IOException, SQLException{
ModelEditStudent student=(ModelEditStudent)tables.getSelectionModel().getSelectedItem();
String sql="DELETE FROM student WHERE nr_indeksu=?";
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Usuwanie studenta");
alert.setHeaderText(null);
alert.setContentText("Czy na pewno chcesz usunÄ…c tego studenta z listy?");
Optional <ButtonType> action = alert.showAndWait();
if(action.get() == ButtonType.OK){
tables.getItems().removeAll(tables.getSelectionModel().getSelectedItem());
try{
try (Connection myConn = ConnectionManager.getConnection()) {
try (PreparedStatement st = myConn.prepareStatement(sql)) {
st.setString(1, student.getNr_indeksu());
st.executeUpdate();
}
myConn.close();
}
}catch (SQLException e){
System.out.println(e);
}
}
and there's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails
(`wu`.`oceny`, CONSTRAINT `oceny_ibfk_3` FOREIGN KEY (`nr_indeksu`)
REFERENCES `student` (`nr_indeksu`))
All the point of this operation is about selecting the row and removing from the database after pressing a button. By now it works only for the listview, but it doesn't remove records from the database.
Anyone got an idea how make it work?
I believe the problem is in your DB schema. try fixing the foreign keys dependencies.I mean the value of nr_indeksu exists in another table of your DB.
You have a table called oceny which has a column nr_indeksu that contains student ids. You have created a foreign key constraint on that table, which requires those student ids to match up with something in the student table.
If you try to delete something in the student table that's referenced by the oceny table, you will get this error, because otherwise, it would leave the database in a state where the oceny table references a student that doesn't exist.
There are a number of solutions to this. You will need to think about what should actually happen in this case - what do you want to have happen to the oceny rows when you delete a matching student.
One option would be for you to change the foreign key to make it do a "cascade delete" - that is, the oceny automatically gets deleted in the same transaction as the student. There's some information here on how to do that.

Retrieving Data from multiple tables from Database

I have some tables in a database. They have some particular pattern. For example, consider I have table employee, then some other table with same pattern like:
table 1:employee
table 2:employee_X
table 3:employee_Y
I want to check if these tables contain data or not and if they do then I have to call some method for each table. I am using following code to retrieve.
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, "My_Table_Name", new String[] {"TABLE"});
while (res.next()) {
if(rs.getStrin(3).equals(employee)){
//my code to write data of this table to a file
}
if(rs.getString(3).equals(employee_X)){
//my code to write data to the same file
}
if(rs.getString(3).equals(employee_Y)){
//code to write data to the same file from this table
}
}
The code is working fine, but how I can retrieve data from all these tables at once instead of using three checks. If any of these table contains data I want to write it to my file. How I can perform this operation in less lines of code and efficiently?
It would be great if anyone can suggest way to check each of these table either contain data or not in a single statement and then I can call my code to write data to file.
You can use UNION statement in your complex query. Please, check example:
SELECT id, name FROM employee WHERE id = ?
UNION
SELECT id, name FROM employee_x WHERE id = ?
UNION
...
Also you can use UNION ALL statement instead of UNION. The main difference that UNION returns unique result set without duplicates, UNION ALL allows duplicates. Please, check this link https://www.w3schools.com/sql/sql_union.asp for detailed explanation about union statement.
If you need create UNION query with custom filtered tables, please check example:
Set<String> requiredTables = new HashSet<>();
// fill set with required tables for result query
requiredTables.add("employee");
ResultSet res = meta.getTables(null, null, "My_Table_Name",
new String[] {"TABLE"});
List<String> existentTables = new LinkedList<>();
while(res.next()) {
if (requiredTables.contains(res.getString(3)) {
existentTables.add(res.getString(3));
}
}
String query = existentTables.stream().map(table -> String.format("SELECT * FROM %s", table)).collect(Collectors.joinning(" UNION "));

Java PreparedStatement multiple batch inserts with foreign keys

I have a Java application and am trying to do a series of batch inserts to a MySQL database. However, many of my tables are linked by foreign keys. So I don't know the value of the foreign keys to use because they are generated in a previous batch.
For example take these two tables:
parent
id
name
child
id
parent_id (required foreign key to parent.id)
name
I know how to import these without using batches:
//already initialized variables: Connection connection, List<ParentObject> parentObjects
ResultSet rs = null;
PreparedStatement psParent = null;
PreparedStatement psChild = null;
for(ParentObject parent: parentObjects){
psParent = connection.prepareStatement("INSERT INTO product (name) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
psParent.setString(1, parent.getName());
psParent.executeUpdate();
int parentId = 0;
rs = psParent.getGeneratedKeys();
if (rs.next())
parentId = rs.getInt(1);
rs.close();
psParent.close();
for(ChildObject child : parent.getChildren()){
psChild = connection.prepareStatement("INSERT INTO child (parent_id, name) VALUES (?,?)");
psChild.setInt(1, parentId);
psChild.setString(2, child.getName());
psChild.executeUpdate();
psChild.close();
}
}
Now I am trying to use batches:
PreparedStatement psParent = connection.prepareStatement("INSERT INTO product (name) VALUES (?)");
PreparedStatement psChild = connection.prepareStatement("INSERT INTO child (parent_id, name) VALUES (?,?)");
for(ParentObject parent: parentObjects){
psParent.setString(1, parent.getName());
psParent.addBatch();
for(ChildObject child : parent.getChildren()){
psChild.setInt(1, I_DONT_KNOW_HOW_TO_GET_THIS_ID_WHICH_HASNT_BEEN_INSERTED_YET);
psChild.setString(2, parent.getName());
psChild.addBatch();
}
}
psParent.executeBatch();
psParent.close();
psChild.executeBatch();
psChild.close();
The actual data structure I am using is much more complicated than what I have above, but it illustrates the basic issue. How would I do the above using batches? The issue I am running into is the child objects cannot be inserted without first knowing the parent_id foreign key to use.
I've searched for answers elsewhere and I cannot find anything to resolve this. I read something about using a stored procedure (which I would like to avoid if possible). Efficiency is important here since I am dealing with potentially millions of records. I appreciate any insight anyone might have.
Don't think it's possible with generated primary key. If your application is only one client for the database maybe you can calculate primary keys by yourself and pass them directly in prepared statements.

Java - Persistence and Entity Classes

I have created a number of entity classes from the database using the JPA.
These are the classes:
Flights
Passengers
PassengersFlights (containing primary key of passengers and flights)
Users
In the database, there are two foreign keys in the PassengersFlights table - one to Flights and one to Passengers.
The only problem I have is that the primary keys of passengers and flights are of data type Passengers and Flights in the PassengersFlights entity class. However, the data types of these in their respective entity classes are String and int, as defined in the database.
I have the following code to update the PassengersFlights table:
// Updating the Passengers_Flights table
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/flights_db", "root", "hello");
EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Flights_AssignmentPU");
EntityManager em = emFactory.createEntityManager();
PassengersFlights booking = new PassengersFlights();
booking.setPassportNum(passport);
booking.setFlightId(flight_id);
em.getTransaction().begin();
em.persist(booking);
em.getTransaction().commit();
em.close();
}
catch (Exception e)
{
response.sendRedirect("ErrorPage.html");
}
The problem I am having is when setting the passport number and the flight id. In the project, they are defined as string and int. However, it is expecting Passenger and Flights data types. How can I solve this problem please?
If passport and flight_id are primary keys of their respectable entities, you can use getReference() to obtain a proxy object of required type with the given primary key:
booking.setPassportNum(em.getReference(Passenger.class, passport));
booking.setFlightId(em.getReference(Flight.class, flight_id));
Also note that if Passengers_Flights is just a link table without extra fields you can model the relationship between passengers and flights using #ManyToMany, without separate entity for the link table.

How to check if any object is related to a row in a table with constrain of foreign key

I am using Hibernate and MySql.
I have a 2 tables:
User: id, name, type
City: id, name, type
type: id, name
Where user.type has foreign key to user_type.id. and as well city.
I would like before deleting a row in user_type table, to check if any row from any table is related to it.
my columns are mapped for example:
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "type_id")
How can I do it?
You said
I have around 100 tables like User and City mapped to this value
ok. Hibernate with JPA book says
You may have removed all other references manually
Which implies you should query manually any related Table. But it says if other entity references Type, database constraints prevent any inconsistency and you see a foreign key constraint exception. I Think it is the best way you can check out what you want. Otherwise, you should query manually for any related Table.
try {
userType = (Type) session.load(Type.class, id);
session.delete(userType);
/**
* or JDBCException
* e.getCause()
* e.getErrorCode() - vendor-specific
*/
} catch (HibernateException e) {
// checkout Exception right here e.getCause();
}
All exceptions thrown by Hibernate are fatal. This means you have to roll back the database transaction and close the current Session. So you may want To open a new session.
use native SQL with Hibernate together:
boolean canDeleteType(ind type_id){
Session s = HibernateUtil.getSessionFactory();
s.beginTransaction();
Query q = s.createQuery("SELECT User.type_id From User");
List l = q.list();
if(l.contains(type_id){
return false;
}
return false;
}
and do the same for your City table too.

Categories