Hibernate annotations - date cannot be mapped - java

I've got a problem. I spend over one hour searching through the Internet but I did find nothing....
I have a simple Table class and one of its elements is List of java.util.Date. When I run the program, the exception is shown:
> org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany
> targeting an unmapped class:
> com.model.Time.timetable[java.util.Date].
My config file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3036/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.model.Cinema" />
<mapping class="com.model.Time" />
</session-factory>
</hibernate-configuration>
and my class:
package com.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import info.talacha.filmweb.models.Movie;
#Entity
#Table(name = "Time")
public class Time implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "time_id")
private List<Date> timetable;
#Column(name = "movie")
private Movie movie;
#Column(name = "dubbing")
private boolean dubbing;
#Column(name = "subtitles")
private boolean subtitles;
#Column(name = "threeDimensions")
private boolean threeDimensions;
public Time(){
timetable = new ArrayList<Date>();
dubbing= false;
subtitles = false;
threeDimensions = false;
movie = new Movie();
}
public Time(int id, List<Date> timetable, Movie movie, boolean dubbing, boolean subtitles, boolean is3dMovie) {
super();
this.id = id;
this.timetable = timetable;
this.movie = movie;
this.dubbing = dubbing;
this.subtitles = subtitles;
threeDimensions = is3dMovie;
}
public boolean isThreeDimensions() {
return threeDimensions;
}
public void setThreeDimensions(boolean threeDimensions) {
this.threeDimensions = threeDimensions;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Time(List<Date> timetable, Movie movie,boolean dubbing, boolean subtitles,boolean is3D) {
this.timetable = timetable;
this.dubbing = dubbing;
this.subtitles = subtitles;
this.movie = movie;
this.threeDimensions = is3D;
}
public List<Date> getTimetable() {
return timetable;
}
public void setTimetable(List<Date> timetable) {
this.timetable = timetable;
}
public boolean isDubbing() {
return dubbing;
}
public void setDubbing(boolean dubbing) {
this.dubbing = dubbing;
}
public boolean isSubtitles() {
return subtitles;
}
public void setSubtitles(boolean subtitles) {
this.subtitles = subtitles;
}
#Override
public String toString() {
return "Time [timetable=" + timetable + ", movie=" + movie + ", dubbing=" + dubbing + ", subtitles="
+ subtitles + ", is3DMovie=" + threeDimensions + "]";
}
}
This way of mapping (oneToMany) worked great when I used it for different type... I have no idea what's wrong. I tried few things but they didn't work. I will be grateful for your help!

OneToMany is used to create an association between two entities. java.util.Date is not an entity. It's a basic type. What you want is #ElementCollection.

Try usin #Temporal annotation like this:
#Temporal(value = TemporalType.TIMESTAMP)
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "time_id")
private List<Date> timetable;

Try Date attribut from java.sql.Date to define each Date attributs of the Time class.
See you.

Related

Hibernate doesn't creating table based on entity

After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.
I checked hibernate config, but can't find where is the problem.
I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.
If there are any ideas, please let me know. Thanks.
Entity class:
package com.game.entity;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(schema = "rpg", name = "player")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name", length = 12, nullable = false)
private String name;
#Column(name = "title", length = 30, nullable = false)
private String title;
#Column(name = "race", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Race race;
#Column(name = "profession", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Profession profession;
#Column(name = "birthday", nullable = false)
private Date birthday;
#Column(name = "banned", nullable = false)
private Boolean banned;
#Column(name = "level", nullable = false)
private Integer level;
public Player() {
}
public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
this.id = id;
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.birthday = birthday;
this.banned = banned;
this.level = level;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Boolean getBanned() {
return banned;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Repository class:
package com.game.repository;
import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
#Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {
private final SessionFactory sessionFactory;
public PlayerRepositoryDB() {
Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
#Override
public List<Player> getAll(int pageNumber, int pageSize) {
try(Session session = sessionFactory.openSession()){
NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
nativeQuery.setFirstResult(pageNumber * pageSize);
nativeQuery.setMaxResults(pageSize);
return nativeQuery.list();
}
}
Hibernate configuration:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Full project code with pom.xml is available by link:
https://github.com/gamlethot/project-hibernate-1
1-Hibernate does not recognize your repository. You should not mark repo classes as #Repository because they are not interfaces and in your example they are working like a service. So they can be #Service.
2-Do not implement IPlayerRepository. Mark it as #Repository and just autowire it to your service classes (or use constructor injection and just use like a variable)
Like:
#Service
public class PlayerRepositoryDB {
private IPlayerRepository playerRepository;
public PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR
this.playerRepository = playerRepository;...
3- DB repository classes are implementing IPlayerRepository but it must be marked as #Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).
Like:
#Repository
public interface IPlayerRepository extends JpaRepository<Player, Long> {
//Here are the methods;
}
Here, the Long is the type of primary key of Player class.
Hibernate XML:
<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.useUnicode">true</property>
Connection url:
db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4
As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.
Spring/Hibernate filter:
<form accept-charset="UTF-8">
Problem solved.
It was because of javax.persistence.; import instead of
jakarta.persistence. in entity class.

Foreign key is null while using Hibernate One to One mapping

I'm trying to work with hibernate and I have a class question and a class answer, and there's One To One relation between them, the code is successfully running but the foreign key is null, I don't know why. Here's my code
package io.com.learnHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="question")
public class Question {
#Id
private int questionId;
private String question;
#OneToOne(mappedBy = "question")
private Answer answer;
public Question() {
super();
}
public Question(int questionId, String question, io.com.learnHibernate.Answer answer) {
super();
this.questionId = questionId;
this.question = question;
answer = answer;
}
public Answer getAnswer() {
return answer;
}
public void setAnswer(Answer answer) {
answer = answer;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
package io.com.learnHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="answer")
public class Answer {
#Id
private int aId;
private String answer;
#OneToOne
#JoinColumn
private Question question ;
public Answer() {
super();
}
public Answer(int aId, String answer) {
super();
this.aId = aId;
this.answer = answer;
}
public int getaId() {
return aId;
}
public void setaId(int aId) {
this.aId = aId;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
my hibernate.cfg.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name = "hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
<!-- Assume test is the database name -->
<property name = "hibernate.connection.url">jdbc:mysql://localhost:3306/aliens </property>
<property name = "hibernate.connection.username">root</property>
<property name = "hibernate.connection.password">root</property>
<property name = "hibernate.hbm2ddl.auto">create</property>
<property name = "show_sql">true</property>
<!-- List of XML mapping files -->
<mapping class= "io.com.learnHibernate.Question"/>
<mapping class= "io.com.learnHibernate.Answer"/>
</session-factory>
</hibernate-configuration>
and my main function
package io.com.learnHibernate;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
import com.mysql.cj.xdevapi.SessionFactory;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//configuration
Configuration conf=new Configuration();
conf.configure("Hibernate.cfg.xml");
org.hibernate.SessionFactory factory=conf.buildSessionFactory();
//creating answer
Answer a1=new Answer();
a1.setaId(180);
a1.setAnswer("my name is hafida");
//creating question
Question q1=new Question();
q1.setQuestionId(3);
q1.setQuestion("wht is your name?");
q1.setAnswer(a1);
//session
Session s=factory.openSession();
Transaction tx=s.beginTransaction();
//save
s.save(q1);
s.save(a1);
tx.commit();
// s.close();
// factory.close();
}
}
I expected to have the value of the foreign key inserted, but it's null
You need to specify cascade type in your entities mapping:
#Entity
#Table(name="answer")
public class Answer {
#Id
private int aId;
private String answer;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn
private Question question;
// ...
}
#Entity
#Table(name="question")
public class Question {
#Id
private int questionId;
private String question;
#OneToOne(mappedBy = "question", cascade = CascadeType.ALL)
private Answer answer;
// ...
}
As you use bidirectional #OneToOne, you should make both sides in-sync:
Answer a1 = new Answer();
a1.setaId(180);
a1.setAnswer("my name is hafida");
Question q1 = new Question();
q1.setQuestionId(3);
q1.setQuestion("wht is your name?");
// make both sides in-sync
a1.setQuestion(q1);
q1.setAnswer(a1);
Then you can save it in this way:
s.save(q1);
// you need not use s.save(a1);
// a1 will be saved due to propagation of the q1 entity's state

How to properly use JPA/Hibernate?

I'm trying to understand annotations better with JPA / Hibernate and SQL Server.
I created a simple project: an abstract class named "Articles". Two classes inherit it: Ramette which adds a weight and Pen which adds a color. The code below is not working and I am unable to correct the errors. Do you have an idea? Thank you!
package fr.eni.hibernate.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity
#Table(name = "Articles")
#Inheritance( strategy = InheritanceType.SINGLE_TABLE )
#DiscriminatorColumn( name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Articles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idarticle")
private Integer idarticle;
#Column(name = "reference")
private String reference;
#Column(name = "marque")
private String marque ;
#Column(name = "designation")
private String designation;
#Column(name = "prixUnitaire")
private float prixUnitaire ;
#Column(name = "qteStock")
private int qteStock ;
public Articles() {
}
public Integer getIdArticle() {
return idarticle;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getMarque() {
return marque;
}
public void setMarque(String marque) {
this.marque = marque;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public float getPrixUnitaire() {
return prixUnitaire;
}
public void setPrixUnitaire(float prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public int getQteStock() {
return qteStock;
}
public void setQteStock(int qteStock) {
this.qteStock = qteStock;
}
#Override
public String toString() {
return "Article [idArticle=" + idarticle + ", reference=" + reference + ", marque=" + marque + ", designation="
+ designation + ", prixUnitaire=" + prixUnitaire + ", qteStock=" + qteStock + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Ramette")
public class Ramette extends Articles {
private static final long serialVersionUID = 1L;
private int grammage;
public Ramette() {
}
#Column(name = "grammage")
public int getGrammage() {
return grammage;
}
public void setGrammage(int grammage) {
this.grammage = grammage;
}
#Override
public String toString() {
return super.toString() + " Ramette [grammage=" + grammage + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Stylo")
public class Stylo extends Articles {
private static final long serialVersionUID = 1L;
private String couleur;
public Stylo() {
}
#Column(name = "couleur")
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur) {
this.couleur = couleur;
}
#Override
public String toString() {
return super.toString() + " Stylo [couleur=" + couleur + "]";
}
}
package fr.eni.hibernate.entities;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class Main {
public static void main(String[] args) throws Exception {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
try {
entityManagerFactory = Persistence.createEntityManagerFactory("WebStore");
entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Articles> query = entityManager.createQuery("from Articles", Articles.class);
List<Articles> art = query.getResultList();
for (Articles article : art) {
System.out.println(art.getClass().getName());
System.out.println("\t" + article);
}
} finally {
if (entityManager != null)
entityManager.close();
if (entityManagerFactory != null)
entityManagerFactory.close();
}
}
}
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns<img src="images/smilies/icon_mad.gif" border="0" alt="" title=":x" class="inlineimg" />si="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="WebStore">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>fr.eni.hibernate.entities.Articles</class>
<class>fr.eni.hibernate.entities.Stylo</class>
<class>fr.eni.hibernate.entities.Ramette</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:sqlserver://localhost;database=PAPETERIE_TEST" />
<property name="javax.persistence.jdbc.user" value="xx" />
<property name="javax.persistence.jdbc.password" value="x" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
CREATE TABLE Articles
(
idarticle INT IDENTITY(1,1),
reference varchar(10) NOT NULL,
marque nvarchar(200) NOT NULL,
designation nvarchar(250) NOT NULL,
prixUnitaire float NOT NULL,
qteStock int NOT NULL,
grammage int NULL,
couleur nvarchar(50) NULL,
type nchar(10) NOT NULL,
CONSTRAINT PK_Articles PRIMARY KEY (idarticle)
)
INSERT INTO Articles (reference, marque, designation, prixUnitaire, qteStock, grammage, couleur, type)
VALUES ('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0, 'Bleu', 'Stylo'),
('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0,'noir', 'Stylo'),
('Clairef', 'CRA4S', 'Ramette A4 Sup', 9, 20, 80, null, 'Ramette');
This makes not much sense. This exception is only thrown when you have a discriminator in the table that has no match in the entity model. Maybe you have trailing spaces in the table?

org.hibernate.QueryException: Unable to resolve path, unexpected token [trying to use left join]

I've created 2 entity classes:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "fr")
public class FR {
#Id
#Column(name = "id")
private String id;
#Column(name = "pid")
private String pId;
#Column(name = "pname")
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
and
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ar")
public class AR {
#Id
#Column(name = "id")
private String id;
#Column(name = "value1")
private String value1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
}
and I'm trying to join these tables to fetch the record.
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123");
but getting an exception:
org.hibernate.QueryException: Unable to resolve path [FR.id], unexpected token [FR] [from entities.FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123]
and when I'm removing FR from the query
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where id=123 or pId=123");
getting another exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from entities.FR left join AR on FR.pId = AR.id where id=123 or pId=123]
I'm in a learning stage of Hibernate and don't know what to do now.
If you've any other info regarding Left Join or the other Joins then please share that too.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/examples?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root#123</property>
<property name="hibernate.show_sql">true</property>
<mapping class="entities.FR"/>
<mapping class="entities.AR"/>
</session-factory>
</hibernate-configuration>
Main Class
package hibernate.joins;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateJoins {
public static void main(String[] args) {
SessionFactory sessionFactory = getSessionFactory();
Session session = sessionFactory.openSession();
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id and ( FR.id=123 or FR.pId=123 )");
List list = qry.list();
list.forEach(System.out::println);
session.close();
sessionFactory.close();
}
public static SessionFactory getSessionFactory () {
SessionFactory sessionFactory = new Configuration().configure("configurations/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
}
Since you are using ON clause in your query, therefore, you can not to use where clause separately. Just keep on adding the condition using AND or OR clause(whichever is applicable)

How to create annotation-based Hibernate mappings?

I am writing a Java project that uses Hibernate ORM and Spring Framework. Right now, when I add a POJO class, I need to modify my hibernate.cfg.xml file, which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="somepackage.class1"/>
<mapping class="somepackage.class2"/>
<!-- etc. -->
</session-factory>
</hibernate-configuration>
Then, I create an annotation-based class. I heard that I could avoid adding per-class mappings in hibernate.cfg.xml if I used proper Hibernate annotations. How can I modify a class to avoid the mappings in an XML file? Here is my example POJO file, generated by NetBeans:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package somepackage.pojo;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author D
*/
#Entity
#Table(name = "ACCOUNT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Account.findAll", query = "SELECT a FROM Account a"),
#NamedQuery(name = "Account.findByLogin", query = "SELECT a FROM Account a WHERE a.login = :login"),
#NamedQuery(name = "Account.findByPassword", query = "SELECT a FROM Account a WHERE a.password = :password")})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "LOGIN", nullable = false, length = 100)
private String login;
#Size(max = 128)
#Column(name = "PASSWORD", length = 128)
private String password;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
private Collection<Comment> commentCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
private Collection<Article> articleCollection;
public Account() {
}
public Account(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlTransient
public Collection<Comment> getCommentCollection() {
return commentCollection;
}
public void setCommentCollection(Collection<Comment> commentCollection) {
this.commentCollection = commentCollection;
}
#XmlTransient
public Collection<Article> getArticleCollection() {
return articleCollection;
}
public void setArticleCollection(Collection<Article> articleCollection) {
this.articleCollection = articleCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (login != null ? login.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Account)) {
return false;
}
Account other = (Account) object;
if ((this.login == null && other.login != null) || (this.login != null && !this.login.equals(other.login))) {
return false;
}
return true;
}
#Override
public String toString() {
return "somepackage.pojo.Account[ login=" + login + " ]";
}
}
I'd suggest you export the hibernate configuration to the spring configuration because of the flexibility that spring provides. Your concern is to not declare the class in the configuration every time you create a new entity. Using spring configuration you can do the following. (packagestoscan property)
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.baeldung.spring.persistence.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
Ref: http://www.javacodegeeks.com/2013/05/hibernate-3-with-spring.html

Categories

Resources