Java - Persistence and Entity Classes - java

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.

Related

solution with JAVA or Postgres for insertion in database

(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.

Error inserting a new entity into the database because it conflicts with a duplicate key value

Im trying to create CRUD test to show my JPA program works but it is giving me strange error when i create a new entity and commit it to the database.
The Table supplier have only one contraint and that is a unique index that is autogenerated.
i will post the classes first then what i tried to do with them
Here is the SQL for the table and contraints
-- DDL for Table SUPPLIER
CREATE TABLE SUPPLIER
( SUPPLIERID INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY,
COMPANYNAME VARCHAR(40),
CONTACTNAME VARCHAR(30),
CONTACTTITLE VARCHAR(30),
ADDRESS VARCHAR(60),
CITY VARCHAR(15),
POSTALCODE VARCHAR(10),
COUNTRY VARCHAR(15),
PHONE VARCHAR(24),
FAX VARCHAR(24)
);
-- Constraints for Table SUPPLIER
ALTER TABLE SUPPLIER ALTER SUPPLIERID NOT NULL;
ALTER TABLE SUPPLIER ALTER COMPANYNAME NOT NULL;
ALTER TABLE SUPPLIER ADD CONSTRAINT PK_SUPPLIER PRIMARY KEY (SUPPLIERID);
This is my suppliers Primary key:
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "SUPPLIERID")
private Integer supplierid;
So first i create the entity and add it to my entitymanager
Supplier sup = new Supplier("Test","Test","Test","Test","Test","Test","Test","Test","Test");
em.persist(p);
Then i save it
public void Save() {
em.getTransaction().begin();
em.getTransaction().commit();
}
And then i get the error below even thought the only constraint that can be broken is 2 identical pk but those are auto generated.
I know that my setup works because my 2 other tests ( inserting other new entities works fine).
I also close and reopen connection between each test.
[EL Warning]: 2014-09-09 17:17:33.67--UnitOfWork(1407675409)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'PK_SUPPLIER' defined on 'SUPPLIER'.
Error Code: -20001
Call: INSERT INTO SUPPLIER (ADDRESS, CITY, COMPANYNAME, CONTACTNAME, CONTACTTITLE, COUNTRY, FAX, PHONE, POSTALCODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [9 parameters bound]
Query: InsertObjectQuery(Peristency.Supplier[ supplierid=null ])
The save method irritates me a little. Like it is written above, it performs an empty transaction, doesn't it? Shouldn't it be something like this:
public void Save() {
...
em.getTransaction().begin();
...
Supplier sup = new Supplier("Test","Test","Test","Test","Test","Test","Test","Test","Test");
em.persist(p);
...
em.getTransaction().commit();
...
}
Could it be, that the coding for the question has been shortened too much, thus scrumbling the picture? Could you provide us please with the complete coding from starting the whole transaction until committing?
I remember once a while, I had a similar problem. Main point was, that I tried to persist twice in one transaction - and that was not possible - complaining about a duplicated key problem. May be that this is a hint for your case.
Okay after alot of Wall to face action i have found the cause of my problem
If you try to commit(entitymanager.getTransaction.commit()) a entity with a null pk to the database it wont work even if the database is supposed to provide the id.
What i had to do everytime i need a new object in a state where it can be saved to the db
public void addEmployee(Employee p) {
em.getTransaction().begin();
em.persist(p);
//Doesn't have an id
System.out.println(p.getEmployeeid());
em.flush();
//now it has an id!
System.out.println(p.getEmployeeid());
em.getTransaction().commit();
}
Then later i can merge and commit at my leasure but i feel like i made a ineffecient solution with the database transaction i have.

Hibernate, search by primary key returns all from table

I have this issue with Hibernate that when i try to retrieve unique result using criteria hibernate returns all the content from the table.
Session session = HibernateUtil.beginTransaction();
Customer c = new Customer();
c.setCustId(custId);
Example ex = Example.create(c);
Criteria criteria = HibernateUtil.getSession().createCriteria(Customer.class);
criteria.add(ex);
Customer customer = (Customer)criteria.uniqueResult();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
However querying the table with:
Customer customer = (Customer)session
.createSQLQuery("select * from customer_ where custid = :id")
.addEntity(Customer.class)
.setInteger("id", custId)
.uniqueResult();
returns correct entry.
custId is the table's primary key. And the Customer class contains 2 #OneToMany mappings.
Do I need to add something to the criteria example above??
The documentation says:
Version properties, identifiers and associations are ignored.
(emphasis mine)
Why not simply using Session.get() if you have the identifier?

jpa update for objects having comosite primary key

I have a composite primary key for my object.How can i use a jpa to update my object?
Normally we use the following code
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa");
EntityManager em = emf.createEntityManager();
Student stud1 = em.find(Student.class,1);
stud1.setSname("Deepak");
//set others
em.merge(stud1);
em.getTransaction().commit();
Now if i have a object whose primary key is composite then how can i implement update?
Pretty much the same, except that you'll have to construct the primary key object:
Student stud1 = em.find(Student.class, new StudentPK(pkPart1, pkPart2));

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