Dto class not creating mysql db table if Transient object values used - java

#Entity
#Table(name="timesheet")
public class TimeSheet extends HibernateDaoSupport implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="timesheetid")
private int timesheetid;
#Transient
private Employee employeeName;
-
-
-
}
In the above code I use annotations with hibernate to create tables in mysql backend.
Table is not getting created while running this code .
There is no exception in the console.
I have used the similar code prior to create many tables.Now its not working .
Is there anything i am missing ?
Kindly help.

The point of Hibernate is not to create database tables, but to use them. You may ask Hibernate to create the schema for you in development, but that should be used only for quick prototyping, and certaily not on a production database.
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#configuration-misc-properties. You must use the hibernate.hbm2ddl.auto property to tell Hibernate to create or update database tables when the session factory is created.

Related

ID of java objects not synchronizing with database

The only link I found that's close to what I am experiencing is this one :
How do you synchronize the id of a java object to its associated db row?
and there's not much of a solution in it.
My problem is that my Java objects aren't updated after being added to my database despite the .commit()
em.getTransaction().begin();
System.out.println(eleve.getID());
em.persist(eleve);
em.getTransaction().commit();
System.out.println(eleve.getID());
which refers to this class
public class Eleve {
private String _nom;
private String _prenom;
private float _ptsMerite;
#Id
private int _IDEleve;
and yields this output :
0
0
I think I've done everything properly when it comes to the persistence since it does create the object in the database (mySQL) with correct ID's which I've set to be autoincrement.
I am using javax.persistence for everything (annotations and such).
Did you try to add the #GeneratedValue annotation at your ID field?
There are four possible strategies you can choose from:
GenerationType.AUTO: The JPA provider will choose an appropriate strategy for the underlying database.
GenerationType.IDENTITY: Relies on a auto-increment column in your database.
GenerationType.SEQUENCE: Relies on a database sequence
GenerationType.TABLE: Uses a generator table in the database.
More info: https://www.baeldung.com/jpa-strategies-when-set-primary-key
If you ever change to a more powerful framework it is likely that this manages your transactions (CMT) so you can't (or don't want) commit everytime you want to access the ID for a new entity. In these cases you can use EntityManager#flush to synchronize Entity Manager with database.

Spring boot SQL script manually

I got a task, to create a basic app with some database handling.
I'm really new at this, the whole spring boot and stuff.
I did all the GET, PUT, POST, DELETE stuff without writing any line of SQL, starts with table creation.
But they asked me to provide the SQL script, how I managed to create the database structure, connections and stuff.
How can I solve this problem?
Add following to spring.jpa.properties
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata
Please refer this article https://www.baeldung.com/spring-data-jpa-generate-db-schema by #baeldung for more detail.
The most simple way to do this is to create in the resources folder a file named schema.sql with all your queries concerning the DDL (tables creation...) and a data.sql if needed where you can add INSERT queries to populate your database.
In the application.properties then you have to add spring.jpa.hibernate.ddl-auto=none to disable the schema creation of JPA and let Spring Boot executes those scripts at startup automatically.
If you want something more powerful, you should try Liquibase or Flyway.
You can used Jpa Like JpaRepository interface. You don't need write any SQL query we use it just used config your data base into Application.Property like database type
Your user name and password
public interface UserRepository extends CrudRepository<User, Integer> {}
when execute this code you can used create user , get find all user , find user by id , delete user and update user
and used #Entity annotaion into Entity class
the Entity class Represent Table into your database
#Entity
#Table(name="user")
public class User{
#Colume(name="id")
private Long id;
#Colume(name="name")
private String name;
//getter and setter here
}
when run this class your data base contract User table with id and
name
this link create spring boot application with database
https://spring.io/guides/gs/accessing-data-mysql/

Changing package name of hibernate managed entities

After doing some refactoring moving some classes into different packages, I started seeing following error while querying the database with criteria builder:
java.lang.IllegalArgumentException: Parameter value [in.helpi.ironlegion.db.hibernate.entity.UserEntity#1863fc] did not match expected type [in.helpi.ironlegion.cerebro.db.hibernate.entity.UserEntity
If I change the package name back to in.helpi.ironlegion.cerebro.db.hibernate.entity it works just fine.
Update
I am able to properly fetch Individual entities. But when I go for querying entities having reference to other entity I get this error. For example:
public class CommunityAccessEntity extends BaseEnity {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#ManyToOne
#JoinColumn(name = "UserEntity_id")
private UserEntity userEntity;
...
}
If I query it on user using criteria builder like:
query.select(root).where(criteriaBuilder.equal(root.get(CommunityAccessEntity_.userEntity), user)));
I get the above error.
Has somebody also faced similar issues..
You must have implemented Serializable interface in your entity classes as it is one of the thumb rules of entity class.
Java serialization is tightly coupled with class name and package name. Your data is stored in database with your old package entity. Now you changed the package name and system will not be able to find the records in DB with your new package. This is why when you restore the package, it works.
If you are using xml based configuration for hbm, please check hbm files whether new package have been updated in all the places.

Is it possible to map a normal Java bean for Hibernate in a separate class / file?

I have a normal model class
public class Person {
private int id;
private String name;
...
}
It's a model class and doesn't have any JPA / Hibernate annotations used.
Is it possible to somehow tell Hibernate to make this class persistent?
I want to use Person in queries, criteria etc, but don't want to introduce annotations to that class (it is defined in a model JAR with no JPA dependency, and I have the DB code in a different JAR);
Hibernate supports XML mappings to map a class to a database, as well as annotations.

Extend entity classes with composite keys in hibernate

In our company we have a strange database model which can't be modified because to many systems works with them. Up to know we have a straight java application which connects with hibernate to the database and loads the data. We have for each table one xml mapping file.
The strange thing about the database is that we do not have any primary keys. Most table have a unique index containing several columns.
Now we want to use an application server (jboss) and the ejb model. So I created a class like this:
#Entity
#Table (name = "eakopf_t")
public class Eakopf implements Serializable {
#Embeddable
public static class EakopfId implements Serializable {
private String mandant;
private String fk_eakopf_posnr;
// I removed here the getters and setters to shorten it up
}
#Id
private EakopfId id;
private String login;
// I removed the getters and setters here as well
}
This works perfect.
Because our customers have different versions of the database schema I thought about extending this class on each database release change. So each interface we create with java can decide which version of the table will be used.
Here is the extended table class
#Entity
#Table (name = "eakopf_t")
public class Eakopf6001 extends Eakopf implements Serializable {
private String newField;
// getters and setters
}
If I use Eakopf (the base version) it is working if I do something like that:
EakopfId id = new EakopfId();
id.setMandant("001");
id.setFk_eakopf_posnr("ABC");
Eakopf kopf = (Eakopf) em.find(Eakopf.class, id);
But if I do this:
EakopfId id = new EakopfId();
id.setMandant("001");
id.setFk_eakopf_posnr("ABC");
Eakopf6001 kopf = (Eakopf6001) em.find(Eakopf6001.class, id);
this exception occues
javax.ejb.EJBException: javax.persistence.PersistenceException:
org.hibernate.WrongClassException: Object with id:
de.entity.Eakopf$EakopfId#291bfe83 was not of the specified subclass:
de.entity.Eakopf (Discriminator: null)
Does anybody has an idea?
many greetings,
Hauke
Doing what you did means to Hibernate that you're storing two different kinds of entities in a single table. This is possible is you use a discriminator column. But if I understand correctly, you just want one kind of entity in the table : Eakopf6001. In this case, its base class should be annotated with #MappedSuperClass, not with #Entity.
I would suggest creating a class annotated with #MappedEntity (let's call it BaseEakopf), and two entities: EaKopf and EaKopf6001, each with their set of additional fields. Include one of the other of the entities in the list of mapped classes, depending on which one you want to use.
My personal opinion is that if you have multiple versions of your app, they should use the same entities, but with different fields. Your version control system would take care of these multiple versions, rather than your source code (i.e. have one set of source files per version of the app, rather than one single set of source files for all the possible versions).

Categories

Resources