Insert data into table using Hibernate - java

I'm new to Hibernate. I want to insert data into this hibernate entity:
#Entity
public class Invitation implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "invited_on")
#Temporal(TemporalType.TIMESTAMP)
private Date invitedOn;
#Column(name = "invited_email")
private String invitedEmail;
#Column(name = "invitation_msg")
private String invitationMessage;
private Boolean status; //true:accepted || false:pending
#ManyToOne
#JoinColumn(name = "sent_by")
private Person inviter;
// getters and setters
}
I tested this code:
public void insert()
{
Query query = session.createQuery("insert into Invitation(invited_on, invited_email, invitation_msg, sent_by)");
int result = query.executeUpdate();
}
What is the proper way to insert data? How I should create session Object?

use this in the main class it works to insert data into table:
Users user = new Users();
user.setUid(1);
user.setUfname("firstname");
user.setUlname("Lastname");
Configuration config = new Configuration()
.configure()
.addAnnotatedClass(Users.class);
ServiceRegistry reg = new ServiceRegistryBuilder()
.applySettings(config.getProperties())
.buildServiceRegistry();
SessionFactory sf = config.buildSessionFactory(reg);
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();

You have Hibernate and it's tools USE THEM!!!
DISCLAIMER:
Example took from HERE
code written on the fly!!
I didnt use status attribute because is not mapped!
// don't need if you already got a session
Session session = HibernateUtil.getSessionFactory().openSession();
// start transaction
session.beginTransaction();
// create invitation Object
Invitation inv = new Invitation();
inv.setId(1L);
inv.setInvitedOn(new java.util.Date());
inv.setInvitedEmail("yo#yo.com");
inv.setInvitationMessage("come on!!!");
inv.setInviter(new Person("inviter")); // hey! this is not valid for sure! :)
// Save the invitation to database
session.save(inv);
// Commit the transaction
session.getTransaction().commit();

Related

org.hibernate.LazyInitializationException when I pass the query result to the toJson() function

I got a list of objects where a save the result of a query using hibernate. The query works fine and print me out the right result. The problem is when I try to pass this list of object to the Gson function called toJson.
Here it is my code:
List<Conversazione> conversations;
SessionFactory factory = new Configuration()
.configure("hibernate2.cfg.xml")
.addAnnotatedClass(Conversazione.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
try {
session.beginTransaction();
//HERE IT IS MY QUERY
conversations = session.createQuery("from Conversazione ").list();
session.getTransaction().commit();
}
finally {
factory.close();
}
//when I print it everything is fine
System.out.println(conversations);
Gson gson = new Gson();
//this is where the problem come from
String json = gson.toJson(conversations);
System.out.println(json);
Here it is the error that it gives me:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: database.Conversazione.partecipanti, could not initialize proxy - no Session
Here it is my Conversazione class:
#Entity
#Table(name="conversazione")
public class Conversazione {
#Id
#Column(name="id")
#NotNull
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="nome", length = 128)
private String nome;
#Column(name="foto", length = 256, nullable = true)
private String foto;
#OneToMany(mappedBy = "idConversazione")
private List<Partecipante> partecipanti = new ArrayList<>();
#OneToMany(mappedBy = "conversazioneId")
private List<Messaggio> messaggi = new ArrayList<>();
#Temporal(TemporalType.TIMESTAMP)
#Column(name="data_creazione", nullable = false)
private Date dataCreazione;
public Conversazione() {
this.nome = nome;
this.foto = foto;
this.dataCreazione = dataCreazione;
}
I have also tried to create a list of Conversazione objects and pass it to the Gson function toJson() and it works fine as it should. So the problem is for sure with hibernate.

why #UniqueConstraint doesn't work in hibernate?

I added unique constraint annotation but still I can insert duplicate entry.
#Entity
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String LastName;
//getter and setter and no-arg constructor
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student student1 = new Student("alireza", "rayani");
Student student2 = new Student("alireza", "rayani");
session.save(student1);
session.save(student2);
session.getTransaction().commit();
Finally ,I found out the problem ,I changed dialect from
properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL5Dialect");
to
properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL57Dialect");
The schema for your database is generated by Hibernate? #UniqueConstraint is only used to generate the schema. If the database already exists, you should execute the alter table on it to add the constraint.

IDENTITY_INSERT with JPA

I am attempting to insert some fake data into an SQL Server Express database. I am using some simple code like this:
#Entity
#Table(name = "People")
public class Peeps implements Serializable {
#Id
#Column(name = "ID", columnDefinition = "Decimal(10,0)")
private String id;
#Column(name = "PERSON_NAME")
private String name;
}
I call the entity manager to create the above class as follows:
private EntityManager em = createManager();
private EntityTransaction utx = em.getTransaction();
final Peeps entity = new Peeps();
entity.setId("10002");
entity.setName("Joe");
utx.begin();
em.persist(entity);
utx.commit();
However, when doing this, I get an error::
Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF
So what I tried doing is something like this:
em.createNativeQuery("SET IDENTITY_INSERT People ON").executeUpdate();
em.persist(entity);
em.createNativeQuery("SET IDENTITY_INSERT People OFF").executeUpdate();
However, I still get the same error. My intuition leads me to believe that the connection is not being shared. Is there something I can do to instruct hibernate to set IDENTITY_INSERT to ON before I invoke my persistence?
You are missing the next line under your id field:
#GeneratedValue(strategy=GenerationType.IDENTITY)
So your id field should look like this:
#Entity
#Table(name = "People")
public class Peeps implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID", columnDefinition = "Decimal(10,0)")
private String id;
#Column(name = "PERSON_NAME")
private String name;
}
Second, you are not supposed to set an ID to your entity by yourself, the ID will be generated automatically when you'll persist it using hibernate.
so get rid of: entity.setId("10002");
and just do this:
private EntityManager em = createManager();
private EntityTransaction utx = em.getTransaction();
final Peeps entity = new Peeps();
entity.setName("Joe");
utx.begin();
em.persist(entity);
utx.commit();
something else make sure that you configured your primary key in your DB table, with auto increment.

Retrieve data from many-to-many relationship - Hibernate

I have a 'User' class:
public class User implements Serializable {
#Id
#GeneratedValue
int id;
String nome;
#Column(unique = true)
String email;
#ManyToMany
#JoinTable (name = "user_roles", joinColumns=
{ #JoinColumn (name = "user_id")}, inverseJoinColumns=
{ #JoinColumn (name = "role_id")})
private List<Role> roles;
I have a 'Role' class:
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
int id;
#Column(unique = true)
String role;
Relationship :An User has roles, and roles has users. I have a many-to-many relationship here. The relation is unidirectional, and my dominant entity is User.
In my database has a table named "user_roles", created automatically. I have a User registered with two roles.
When I retrieve the User from my database using a "UserDao" class, and I try to access the roles of the user, I get NullPointerException. I got all others informations (name, email, etc), but the roles I can not access.
My 'UserDao' class:
public class UserDaoImpl implements UserDao{
private static final transient Logger log = LoggerFactory.getLogger(UserDaoImpl.class);
private final String HIBERNATE_CFG = "data.cfg.xml";
#Override
public int insertUser (User user){
int code = 0;
Session session = new HibernateUtil(HIBERNATE_CFG).getSessionFactory().getCurrentSession();
try {
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
code = 1;
}
catch (Exception e) {
log.error(e.getMessage());
session.getTransaction().rollback();
code = 0;
}
return code;
}
#Override
public List<User> getAll() {
Session session = new HibernateUtil(HIBERNATE_CFG).getSessionFactory().getCurrentSession();
List<User> users = null;
try
{
session.beginTransaction();
String queryString = "SELECT * FROM USER;";
SQLQuery consulta = session.createSQLQuery(queryString);
consulta.setResultTransformer(Transformers.aliasToBean(User.class));
users = (List<User>) consulta.list();
session.getTransaction().commit();
}
catch(ConstraintViolationException e)
{
log.error(e.getMessage());
session.getTransaction().rollback();
}
return users;
}
I tried using iterator:
List roles = user.getRegras();
for (Iterator it = roles.iterator(); it.hasNext();){
Role r = (Role) it.next();
out.println("Role:" + r.getRole());
}
I tried to instantiate the variable "roles" in the 'User' class like below. But every time the variable returns size 0:
#ManyToMany
#JoinTable (name = "user_roles", joinColumns=
{ #JoinColumn (name = "user_id")}, inverseJoinColumns=
{ #JoinColumn (name = "role_id")})
private List<Role> regras = new ArrayList<Role>();
I tried getting the roles from Object User, but I receive a NullPointerException when the method size() is called.
List<Role> roles = (List<Role>)user.getRoles();
out.println("size roles: " + roles.size());
I'm trying to acess my table 'user_roles' to retrieve the data from database, but I can't dothis. Can anyone help me?
Thanks in Advance
You're using a SQL query to load the users, and mapping the result to the entity. So what you get is detached entities, containing only what the SQL query returned.
Learn to use JPQL/HQL, and to load entities, which will then be managed:
String queryString = "SELECT u FROM User u";
Query consulta = session.createQuery(queryString);
users = (List<User>) consulta.list();

Wicket/Hibernate: get duplicated records in list from db

I´m using wicket and hibernate. I got two objects category and group. A group can have several categorys and a category can have several groups.
My Problem (its pretty hard for me to explain it in english):
It seems that in my list I get from the database are equal objects as the size of the categorys I store to the group (while in the database is only ONE group).
Example:
Categorys
1, 2, 3, 4
Group test
test got the category 1 and 2. So in my panel the group test shows twice. If I would add the category 3 the group test would been showed three times.
this is how I get data of my database:
public List<T> getAll( Class theClass) {
List<T> entity = null;
Transaction trns = null;
Session session = sessionFactory.openSession();
try {
trns = session.beginTransaction();
entity = session.createCriteria(theClass).list();
session.getTransaction().commit();
} catch (RuntimeException e) {
e.printStackTrace();
}finally {
session.flush();
session.close();
}
return entity;
}
inside my panel I get a list of my groups like this:
List<Group> groupList = new ArrayList<Group>();
groupList = groupDao.getAll(Group.class);
if I debug through my panel and hold on at this page in groupList is the SAME object equal to the size of categorys stored to the group. Inside the database is still only ONE row.
Group entity:
#Entity
#Table(name = "GROUP_USER")
public class Group implements Serializable{
#Id
#GeneratedValue
#Column(name = "GROUP_ID")
private int groupID;
#ManyToMany(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
#JoinTable(name="GROUP_TO_CATEGORY",
joinColumns={#JoinColumn(name="GROUP_ID")},
inverseJoinColumns={#JoinColumn(name="CATEGORY_ID")})
private Set<Category> categorys = new HashSet<Category>();
//constructor.. getter and setter..
}
Category entity:
#Entity
#Table(name = "CATEGORY")
public class Category implements Serializable{
#Id
#GeneratedValue
#Column(name = "CATEGORY_ID")
private int categoryId;
#ManyToMany(mappedBy="categorys", fetch = FetchType.EAGER)
private Set<Group> groups = new HashSet<Group>();
//constructor.. getter and setter..
}
This is caused by your use of eager fetching, which is usually a bad idea anyway.
You should try to change your mapping to do lazy fetching of collections if at all possible. That will solve this issue and any new issues it introduces can be better handled by other means such as "Open Session in View". You can see some discussion of that in this question.
If you have a fetch that really must be done eagerly, however, you can correct this issue by using a ResultTransformer that consolidates the duplicates as follows:
public List<T> getAll( Class theClass) {
List<T> entity = null;
Transaction trns = null;
Session session = sessionFactory.openSession();
try {
trns = session.beginTransaction();
Criteria criteria = session.createCriteria(theClass);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
entity = criteria.list();
session.getTransaction().commit();
} catch (RuntimeException e) {
e.printStackTrace();
}finally {
session.flush();
session.close();
}
return entity;
}

Categories

Resources