The target entity of the relationship attribute cannot be determined - java

I can't figure out what the problem is, please help. I've searched a lot, but didn't find any useful advice. Maybe you can help me. Thanks a lot.
There are two classes using eclipselink as jpa provider:
#Entity
#Table(name = "USER")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String login;
private Long groupId;
private String email;
#ManyToMany(mappedBy = "users")
private List polls;
#OneToMany(mappedBy = "user")
private List votes;
public List getVotes() {
return votes;
}
public void setVotes(List votes) {
this.votes = votes;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List getPolls() {
return polls;
}
public void setPolls(List polls) {
this.polls = polls;
}
}
and
#Entity
#Table(name = "VOTE")
public class Vote {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long vid;
private String comment;
#ManyToOne
private User user;
#ManyToOne
private Option option;
public Vote() {
}
public Long getVid() {
return vid;
}
public void setVid(Long vid) {
this.vid = vid;
}
#Column(name = "comment")
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Option getOption() {
return option;
}
public void setOption(Option option) {
this.option = option;
}
}
When I'm trying to compile this, I receive error:
Exception [EclipseLink-7214] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The target entity of the relationship attribute [votes] on the class [class logic.User] cannot be determined. When not using generics, ensure the target entity is defined on the relationship mapping.
Here is my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="pollsPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>logic.Option</class>
<class>logic.Poll</class>
<class>logic.User</class>
<class>logic.Vote</class>
<class>logic.Greeting</class>
<properties>
<property name="eclipselink.jdbc.password" value="" />
<property name="eclipselink.jdbc.user" value="" />
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="eclipselink.jdbc.url"
value="jdbc:mysql://localhost:3306/core_polls" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence>

As stated in the Javadoc
If the collection is defined using generics to specify the element
type, the associated target entity type need not be specified;
otherwise the target entity class must be specified.
So, you can do either
#OneToMany(mappedBy = "user")
private List<Vote> votes;
or
#OneToMany(targetEntity=logic.Vote.class, mappedBy = "user")
private List votes;
But I would prefer the first.

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.

The Keycloak EntityManager can't mapping any model

Keyсloak version 14.0
I have store some custom tables in The Keycloak postgres database, my entity:
public class StoreTestModel {
public StoreTestModel() {
}
public StoreTestModel(Integer id, String fieldOne, String fieldTwo) {
this.id = id;
this.fieldOne = fieldOne;
this.fieldTwo = fieldTwo;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(updatable = false, nullable = false)
private Integer id;
#Column(name = "field_one")
private String fieldOne;
#Column(name = "field_two")
private String fieldTwo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public String getFieldTwo() {
return fieldTwo;
}
public void setFieldTwo(String fieldTwo) {
this.fieldTwo = fieldTwo;
}
}
When i try to get this data by the EntityManager firts of all I have receive the EntityManager:
EntityManager em = jpaConnectionProvider.getEntityManager();
Then I try to get the data from my custom table:
StoreTestModel storeTestModel = em.createQuery("SELECT u FROM store_test_model u WHERE u.fieldOne = :fieldOne", StoreTestModel.class).setParameter("fieldOne", "test one").getSingleResult();
my persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="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">
<persistence-unit name="api-extensions">
<jta-data-source>java:jboss/datasources/KeycloakDS</jta-data-source>
<class>keycloak.apiextension.entity.StoreTestModel</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
but i recive the exception:
ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-611) Uncaught server error: org.keycloak.models.ModelException: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: store_test_model is not mapped [SELECT u FROM store_test_model u WHERE u.fieldOne = :fieldOne]
plese, help me to solve this issue 😢

Can't insert data into database through persistence.xml file

I have created a PostgreSQL script just to insert a row in the customer table. The insert happens when my project is starting to run.
But it doesn't work because I'm getting the following error:
[EL Warning]: 2016-10-23 22:14:40.182--ServerSession(609762439)--?>Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at end of input
Position: 82 Error Code: 0 Call: INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, >Fax, Number) VALUES Query: DataModifyQuery(sql="INSERT INTO customer (id, Name, Adres, >PostalCode, City, Tel, Fax, Number) VALUES") [EL Warning]: 2016-10-23 22:14:40.183--ServerSession(609762439)-->Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): >org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at or near "1"
Position: 2 Error Code: 0 Call: (1, 'Kantoor Snel Transport / Distributiecentrum', >'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92'); Query: DataModifyQuery(sql="(1, 'Kantoor Snel Transport / >Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, >'92');") [EL Info]: connection: 2016-10-23 22:15:02.917-->ServerSession(609762439)-->file:/C:/Users/yomac_000/workspace/.metadata/.plugins/org.eclipse.wst.ser>ver.core/tmp0/wtpwebapps/snel-transport/WEB-INF/classes/_snel-transport >logout successful
Here is the persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="snel-transport" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>nl.cimsolutions.snel_transport.models.Orders</class>
<class>nl.cimsolutions.snel_transport.models.OrderLine</class>
<class>nl.cimsolutions.snel_transport.models.OrderList</class>
<class>nl.cimsolutions.snel_transport.models.Customer</class>
<class>nl.cimsolutions.snel_transport.models.Product</class>
<class>nl.cimsolutions.snel_transport.models.Category</class>
<class>nl.cimsolutions.snel_transport.models.Status</class>
<class>nl.cimsolutions.snel_transport.models.Truck</class>
<!-- <jta-data-source>java:app/snel-transport</jta-data-source> -->
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<properties>
<property
name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
<property name="eclipselink.canonicalmodel.subpackage"
value="dev" />
<property name="javax.persistence.sql-load-script-source"
value="META-INF/sql/Customer2.sql" />
<property name="javax.persistence.schema-generation-target"
value="database" />
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/snel-transport" />
<property name="javax.persistence.jdbc.user" value="transport_user" />
<property name="javax.persistence.jdbc.password"
value="admin" />
<property name="javax.persistence.jdbc.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
And here is my PostgreSQL script:
INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, Fax, Number) VALUES
(1, 'Kantoor Snel Transport / Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92');
And here is how the Customer model looks like:
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(
name = "CustomerGenerator",
allocationSize = 1,
initialValue = 1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE,
generator="CustomerGenerator")
private Long id;
private String name;
private String adres;
#Column(name="Number")
private String streetNumber;
#Column(name="PostalCode")
private String postalCode;
#Column(name="City")
private String city;
#Column(name="Tel")
private String tel;
#Column(name="Fax")
private String fax;
#OneToMany(mappedBy = "customer", targetEntity = Orders.class)
private List<Orders> orders;
public Customer() {
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "model.OrderLine[ id=" + id + " ]";
}
public String getName() {
return name;
}
public String getAdres() {
return adres;
}
public void setName(String name) {
this.name = name;
}
public void setAdres(String adres) {
this.adres = adres;
}
}
I have already tried using the PostgreSQL script in pgAdmin. And there the script works, but somehow it doesn't work in JPA.. Anyone got a clue how I can solve this problem?

Why does Spring close the DB-session in Runnable after first Repository method call?

I'm working on a Spring MVC App with JPA (Hibernate as Provider) and a PostgreSQL database. I wanted to insert results (of a time consuming task) into the database in background and created a serviceclass which implements Runnable. In the run method, I receive an entity from the repository but when I try to access a lazy collection of the entity, the database session is already closed (I get a lazy initialization exception).
The source code of my Background-Service:
#Service
#Scope("prototype")
public class ProjectServiceTestThread implements Runnable{
static Logger log = Logger.getLogger(ProjectServiceTestThread.class);
#Autowired
ProjectRepository projectRepository;
#Autowired
ScenarioRepository scenarioRepository;
#Override
#Transactional
public void run() {
List<Project> projectList = projectRepository.findByName("thread test project");
Project project;
project = projectList.get(0);
//A project can have multiple scenarios
Scenario scenario;
if (project.getScenarios().isEmpty()) { //this line fails -> lazyInitializationException - no Session
System.err.println("Creating new scenario");
scenario = new Scenario();
scenario.setName("thread test scenario");
scenario.setDescription(this + ".runServiceFunction at " + System.currentTimeMillis());
scenario.setProject(project);
scenario = scenarioRepository.save(scenario);
} else {
System.err.println("Using existing scenario");
scenario = project.getScenarios().iterator().next();
}
}
}
The Service and Spring TaskExecutor are Autowired in the Controller which is running on a Tomcat v8.0 Server.
Controller code:
#Autowired
ProjectServiceTestThreadImpl testRunnable;
#Autowired
TaskExecutor taskExecutor;
#RequestMapping(value="openproject", method=RequestMethod.GET)
public String getStringProjects(Map<String, Object> model) throws InterruptedException
{
System.err.println(this + " before call to runnable ");
testRunnable.run();
taskExecutor.execute(testRunnable);
return "openproject";
}
The log shows that the database session closes right after the findByName Query:
09:50:31,438 TRACE JdbcCoordinatorImpl:525 - Closing prepared statement [select distinct project0_.prjid as prjid1_24_, project0_.createdby as createdb2_24_, project0_.createdon as createdo3_24_, project0_.description as descript4_24_, project0_.designtarget as designta5_24_, project0_.location as location6_24_, project0_.name as name7_24_, project0_.modelid as modelid11_24_, project0_.timehorizon as timehori8_24_, project0_.updatedby as updatedb9_24_, project0_.updatedon as updated10_24_ from public.project project0_ where lower(project0_.name) like ('%'||lower('thread test project')||'%')]
09:50:31,438 TRACE JdbcCoordinatorImpl:278 - Starting after statement execution processing [ON_CLOSE]
09:50:31,438 TRACE StatefulPersistenceContext:880 - Initializing non-lazy collections
09:50:31,439 TRACE SessionImpl:357 - Closing session
09:50:31,439 TRACE JdbcCoordinatorImpl:199 - Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl#3b95a16b]
09:50:31,439 TRACE LogicalConnectionImpl:178 - Closing logical connection
09:50:31,439 DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
09:50:31,439 DEBUG LogicalConnectionImpl:264 - Released JDBC connection
09:50:31,442 TRACE LogicalConnectionImpl:190 - Logical connection closed
09:50:31,445 TRACE TransactionSynchronizationManager:243 - Removed value [org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$DefaultCrudMethodMetadata#7cc8f09] for key [public abstract java.util.List eu.cite.repository.ProjectRepository.findByName(java.lang.String)] from thread [myExecutor-1]
09:50:31,451 TRACE LazyInitializationException:53 - failed to lazily initialize a collection of role: eu.cite.model.Project.scenarios, could not initialize proxy - no Session
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: eu.cite.model.Project.scenarios, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:155)
at org.hibernate.collection.internal.PersistentSet.isEmpty(PersistentSet.java:166)
at eu.cite.service.ProjectServiceTestThread.run(ProjectServiceTestThread.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Configuration:
<context:component-scan base-package="eu.cite.repository, eu.cite.service" scoped-proxy="targetClass" />
<jpa:repositories base-package="eu.cite.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit"/>
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<entry key="hibernate.format_sql" value="true"/>
<entry key="hibernate.jdbc.batch_size" value="50"/>
<entry key="hibernate.order_inserts" value="true"/>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<bean id="ModelMapper" class="org.modelmapper.ModelMapper"></bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5432/Cite?autoReconnect=true"></property>
<property name="username" value="cite"></property>
<property name="password" value="***"></property>
</bean>
<task:executor id="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>
Can somebody tell me why it does not work this way? I figured out some ways to make it work, but I don't understand why it does not work with the code above. These three approaches correctly insert the Scenario, without closing the database Session in between:
remove #Service from ProjectServiceTestThread and register the bean in the config manually
Not implement Runnable and annotate the run() method of ProjectServiceTestThread with #Async
Not using the Spring Task Executor
Edit - Project entity:
#Entity
#Table(name = "project", schema = "public", uniqueConstraints = #UniqueConstraint(columnNames = "name"))
public class Project implements java.io.Serializable {
private int prjid;
private SimulationModel simulationmodel;
private String name;
private String description;
private String designtarget;
private Date timehorizon;
private String location;
private Date createdon;
private Date updatedon;
private Integer createdby;
private Integer updatedby;
private Set<ObjectiveFunction> objectivefunctions = new HashSet<ObjectiveFunction>(
0);
private Set<Scenario> scenarios = new HashSet<Scenario>(0);
private Set<ScenarioGenerator> scenariogenerators = new HashSet<ScenarioGenerator>(
0);
private List<Component> components = new ArrayList<Component>();
private Set<OptConstraint> optconstraints = new HashSet<OptConstraint>(0);
private Set<SearchConstraint> searchconstraints = new HashSet<SearchConstraint>(
0);
private Set<Metric> metrics = new HashSet<Metric>(0);
private Set<UserGroupProject> usergroupprojects = new HashSet<UserGroupProject>(
0);
private Set<ExtParam> extparams = new HashSet<ExtParam>(0);
public Project() {
}
public Project(int prjid, String name) {
this.prjid = prjid;
this.name = name;
}
public Project(int prjid, SimulationModel simulationmodel, String name,
String description, String designtarget, Date timehorizon, String location,
Date createdon, Date updatedon, Integer createdby,
Integer updatedby, Set<ObjectiveFunction> objectivefunctions,
Set<Scenario> scenarios, Set<ScenarioGenerator> scenariogenerators,
List<Component> components, Set<OptConstraint> optconstraints,
Set<SearchConstraint> searchconstraints, Set<Metric> metrics,
Set<UserGroupProject> usergroupprojects, Set<ExtParam> extparams) {
this.prjid = prjid;
this.simulationmodel = simulationmodel;
this.name = name;
this.description = description;
this.designtarget = designtarget;
this.timehorizon = timehorizon;
this.location = location;
this.createdon = createdon;
this.updatedon = updatedon;
this.createdby = createdby;
this.updatedby = updatedby;
this.objectivefunctions = objectivefunctions;
this.scenarios = scenarios;
this.scenariogenerators = scenariogenerators;
this.components = components;
this.optconstraints = optconstraints;
this.searchconstraints = searchconstraints;
this.metrics = metrics;
this.usergroupprojects = usergroupprojects;
this.extparams = extparams;
}
#SequenceGenerator(name="project_prjid_seq",sequenceName="project_prjid_seq") #GeneratedValue(strategy = GenerationType.SEQUENCE, generator="project_prjid_seq")
#Id
#Column(name = "prjid", unique = true, nullable = false)
public int getPrjid() {
return this.prjid;
}
public void setPrjid(int prjid) {
this.prjid = prjid;
}
#ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.PERSIST)
#JoinColumn(name = "modelid")
public SimulationModel getSimulationmodel() {
return this.simulationmodel;
}
public void setSimulationmodel(SimulationModel simulationmodel) {
this.simulationmodel = simulationmodel;
}
#Column(name = "name", unique = true, nullable = false, length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "designtarget", length = 50)
public String getDesigntarget() {
return this.designtarget;
}
public void setDesigntarget(String designtarget) {
this.designtarget = designtarget;
}
#Temporal(TemporalType.TIME)
#Column(name = "timehorizon", length = 15)
public Date getTimehorizon() {
return this.timehorizon;
}
public void setTimehorizon(Date timehorizon) {
this.timehorizon = timehorizon;
}
#Column(name = "location")
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "createdon", length = 22)
public Date getCreatedon() {
return this.createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updatedon", length = 22)
public Date getUpdatedon() {
return this.updatedon;
}
public void setUpdatedon(Date updatedon) {
this.updatedon = updatedon;
}
#Column(name = "createdby")
public Integer getCreatedby() {
return this.createdby;
}
public void setCreatedby(Integer createdby) {
this.createdby = createdby;
}
#Column(name = "updatedby")
public Integer getUpdatedby() {
return this.updatedby;
}
public void setUpdatedby(Integer updatedby) {
this.updatedby = updatedby;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ObjectiveFunction> getObjectivefunctions() {
return this.objectivefunctions;
}
public void setObjectivefunctions(Set<ObjectiveFunction> objectivefunctions) {
this.objectivefunctions = objectivefunctions;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<Scenario> getScenarios() {
return this.scenarios;
}
public void setScenarios(Set<Scenario> scenarios) {
this.scenarios = scenarios;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ScenarioGenerator> getScenariogenerators() {
return this.scenariogenerators;
}
public void setScenariogenerators(Set<ScenarioGenerator> scenariogenerators) {
this.scenariogenerators = scenariogenerators;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
#OrderBy("componentid")
public List<Component> getComponents() {
return this.components;
}
public void setComponents(List<Component> components) {
this.components = components;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<OptConstraint> getOptconstraints() {
return this.optconstraints;
}
public void setOptconstraints(Set<OptConstraint> optconstraints) {
this.optconstraints = optconstraints;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<SearchConstraint> getSearchconstraints() {
return this.searchconstraints;
}
public void setSearchconstraints(Set<SearchConstraint> searchconstraints) {
this.searchconstraints = searchconstraints;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<Metric> getMetrics() {
return this.metrics;
}
public void setMetrics(Set<Metric> metrics) {
this.metrics = metrics;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<UserGroupProject> getUsergroupprojects() {
return this.usergroupprojects;
}
public void setUsergroupprojects(Set<UserGroupProject> usergroupprojects) {
this.usergroupprojects = usergroupprojects;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ExtParam> getExtparams() {
return this.extparams;
}
public void setExtparams(Set<ExtParam> extparams) {
this.extparams = extparams;
}
I found the issue in my appConfig.java: There was another component scan, which scanned all packages, including services:
#Configuration
#EnableWebMvc
#ComponentScan({"eu.cite"})
public class appConfig extends WebMvcConfigurerAdapter {
this seems to undo the transaction configuration from the xml. I changed the component scan to eu.cite.controller so my servlet is still able to find the controller and does not interfere with the other config

Hibernate join error: NullPointerException at org.hibernate.hql.ast.HqlSqlWalker.createFromJoinElement

I create this hql in my project (an snack bar), to search all orders that have the product selected by the user as parameter:
select order from Order order, OrderItem item
inner join order.cod_order_item as item
inner join item.cod_product as cod_product
where cod_product = id
However, when I run the createQuery(), gives a nullpointer at org.hibernate.hql.ast.HqlSqlWalker.createFromJoinElement.
What am i doing wrong?
Below, here's my codes:
OrderDAO.java
public class OrderDAO {
private Session session;
public PedidoDAO(Session session){
this.session = session;
}
public List<Order> getAllOrderFromProduct(Product product{
String hql = "select order from Order order, OrderItem item " +
"inner join order.order_item_id as item " +
"inner join item.product_id as product_id " +
"where product_id = '"+ product.getId() + "'";
Configuration cfg = new Configuration();
SessionFactory factory = cfg.configure().buildSessionFactory();
Session session = factory.openSession();
Query query = session.createQuery(hql);
List result = query.list();
return result;
}
}
Order.java (entity)
#Entity
public class Order{
#Id
#GeneratedValue
private Long order_id;
#Column(name="order_date", nullable=false, length=15)
private Date data;
#Column(name="order_total", nullable=false, length=8)
private double total;
/* Relacionamentos */
#Column(name="employee_id", nullable=false, length=8)
private Long employee_id;
#Column(name="customer_id", nullable=false, length=8)
private Long customer_id;
#Column(name="order_item_id", nullable=false, length=8)
private Long order_item_id;
public Long getId() {
return order_id;
}
public void setId(Long order_id) {
this.order_id= order_id;
}
public Date getOrderDate() {
return order_date;
}
public void setOrderDate(Date order_date) {
this.order_date = order_date;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public Long getFuncionario() {
return cod_funcionario;
}
public void setEmployee(Long employee_id) {
this.employee_id= employee_id;
}
public Long getCustomer() {
return customer_id;
}
public void setCustomer(Long customer_id) {
this.customer_id= customer_id;
}
public Long getOrderItem() {
return order_item_id;
}
public void setOrderItem(Long order_item_id) {
this.order_item_id= order_item_id;
}
}
My hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/lanchonete_db</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping class="gigabyte.bean.Customer" />
<mapping class="gigabyte.bean.Address"/>
<mapping class="gigabyte.bean.Employee" />
<mapping class="gigabyte.bean.Order"/>
<mapping class="gigabyte.bean.OrderItem" />
<mapping class="gigabyte.bean.Product"/>
<mapping class="gigabyte.bean.Phone" />
</session-factory>
</hibernate-configuration>
Any help is welcome.
I found my error! I forgot to reference the annotation #ManyToMany in relationship table on Order.java, then the Hibernate tried to get the relationship between the two tables and found nothing. Now, works fine with this query, based on #axtavt answer:
select order from Order order, OrderItem item
inner join order.order_item as item
where item.cod_product = id
My Order.java corrected:
#Entity
public class Order{
#Id
#GeneratedValue
private Long order_id;
#Column(name="order_date", nullable=false, length=15)
private Date data;
#Column(name="order_total", nullable=false, length=8)
private double total;
/* Relationships*/
#Column(name="employee_id", nullable=false, length=8)
private Long employee_id;
#Column(name="customer_id", nullable=false, length=8)
private Long customer_id;
#ManyToMany(targetEntity=OrderItem.class, fetch=FetchType.LAZY)
#Fetch(FetchMode.SUBSELECT)
#JoinTable(name = "order_order_item", joinColumns = { #JoinColumn(name = "cod_order") },
inverseJoinColumns = { #JoinColumn(name = "cod_item") })
public Set<OrderItem> setOrderItem = new HashSet<OrderItem>();
public Long getId() {
return order_id;
}
public void setId(Long order_id) {
this.order_id= order_id;
}
public Date getOrderDate() {
return order_date;
}
public void setOrderDate(Date order_date) {
this.order_date = order_date;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public Long getFuncionario() {
return cod_funcionario;
}
public void setEmployee(Long employee_id) {
this.employee_id= employee_id;
}
public Long getCustomer() {
return customer_id;
}
public void setCustomer(Long customer_id) {
this.customer_id= customer_id;
}
public Set<OrderItem> getOrderItem() {
return orderItem;
}
public void setOrderItem(Set<OrderItem> orderItem) {
this.orderItem= orderItem;
}
}
You certainly don't need to add OrderItem to from explicitly since it's already added by join:
select order from Order order
inner join order.cod_order_item as item
inner join item.cod_product as cod_product
where cod_product = id

Categories

Resources