Can't create entity with Hibernate. SQLGrammarException - java

I spent the whole day to solve this problem. An error occurs on line with session.getTransaction().commit();
private SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
#Override
public void initGroup(Group group) throws BotException {
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
session.persist(group);
session.getTransaction().commit();
} catch (PersistenceException e)
{
throw new BotException("You are already registred");
}
finally {
session.close();
sessionFactory.close();
}
Surprisingly, I have the same function for "Station" entity, but it works fine
It's strange so much. I don't know how to solve it.
It's my Group.class
#Entity
#Table(name = "group")
public class Group {
private String name;
private String password;
private String telegramId;
private int experience;
private int money;
private String nowStation;
public Group() {}
public Group(String name, String password, String telegramId) {
this.name = name;
this.password = password;
this.telegramId = telegramId;
}
#Id
#Column(name = "name", nullable = false, length = 45)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "password", nullable = false, length = 45)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "telegram_id", nullable = false, length = 45)
public String getTelegramId() {
return telegramId;
}
public void setTelegramId(String telegramId) {
this.telegramId = telegramId;
}
#Basic
#Column(name = "experience", nullable = true)
public int getExperience() {
return experience;
}
public void setExperience(int experience) {
this.experience = experience;
}
#Basic
#Column(name = "money", nullable = true)
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
#Basic
#Column(name = "now_station", nullable = true, length = 45)
public String getNowStation() {
return nowStation;
}
public void setNowStation(String nowStation) {
this.nowStation = nowStation;
}
and hibernate.cfg.xml
<?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/game_data_base</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">*******</property>
<mapping class="model.Group"/>
<mapping class="model.Station"/>
<mapping class="model.User"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Errors
сен 25, 2016 7:42:54 PM org.telegram.telegrambots.logging.BotLogger severe
19:42:54.374 [PMPUTestBot Telegram Executor] DEBUG org.hibernate.service.internal.AbstractServiceRegistryImpl - Implicitly destroying ServiceRegistry on de-registration of all child ServiceRegistries
SEVERE: BOTSESSION
19:42:54.374 [PMPUTestBot Telegram Executor] INFO org.hibernate.orm.connections.pooling - HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/game_data_base]
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
19:42:54.374 [PMPUTestBot Telegram Executor] DEBUG org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl - Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1411)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:475)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3168)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2382)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at dao.GroupDaoImpl.initGroup(GroupDaoImpl.java:32)
Thank you :)

Group is an SQL keyword. Rename your table to something else
#Table(name = "my_group")

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.

Hibernate Util Class

I'm trying to rewrite a java app that i had, cause i made many changes to the database.
I did a copy/paste of the HibernateUtil class that i had to my new app. And it just does not seem to work :( .
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static SessionFactory sessionFactory = null;
static {
sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
public static Session getSession() {
Session session = null;
if (threadLocal.get() == null) {
// Create Session object
session = sessionFactory.openSession();
threadLocal.set(session);
} else {
session = threadLocal.get();
}
return session;
}
public static void closeSession() {
Session session = null;
if (threadLocal.get() != null) {
session = threadLocal.get();
session.close();
threadLocal.remove();
}
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
That's the error i get:
Exception in thread "Thread-1" Exception in Application constructor
java.lang.ExceptionInInitializerError
at Mach.lambda$main$0(Mach.java:58)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: Entities.ObjectEntity.info type: object
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:629)
at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:351)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:464)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at Utility.HibernateUtil.<clinit>(HibernateUtil.java:12)
... 2 more
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:473)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:372)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class Mach
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:963)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:875)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
... 1 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class Utility.HibernateUtil
at Models.UserIM.<init>(UserIM.java:18)
at Mach.<init>(Mach.java:30)
... 13 more
Exception running application Mach
Also, i would really appreciate if you could help me build my own. Though FOR NOW, i just want to finish my app. I have worked many days reconstructing the database for new demands, i have almost the whole code ready, and i'm stuck on this :/ feels bad.
I already check my hibernate.cfg.xml file and seems ok!
Here is my Entity class:
package Entities;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Objects;
#Entity
#Table(name = "user_is_worker", schema = "walker", catalog = "")
public class UserIsWorkerEntity {
private String workerId;
private String userLogName;
private String userLogPass;
private String amka;
private String afm;
private BigDecimal salary;
private Byte bonusProgram;
private UserEntity userByWorkerId;
private UserIsWorkerEntity userIsWorkerBySupervisor;
private PermisEntity permisByPermisId;
#Id
#Column(name = "WorkerID", nullable = false, length = 20)
public String getWorkerId() {
return workerId;
}
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
#Basic
#Column(name = "UserLogName", nullable = true, length = 15)
public String getUserLogName() {
return userLogName;
}
public void setUserLogName(String userLogName) {
this.userLogName = userLogName;
}
#Basic
#Column(name = "UserLogPass", nullable = true, length = 15)
public String getUserLogPass() {
return userLogPass;
}
public void setUserLogPass(String userLogPass) {
this.userLogPass = userLogPass;
}
#Basic
#Column(name = "AMKA", nullable = true, length = 12)
public String getAmka() {
return amka;
}
public void setAmka(String amka) {
this.amka = amka;
}
#Basic
#Column(name = "AFM", nullable = true, length = 9)
public String getAfm() {
return afm;
}
public void setAfm(String afm) {
this.afm = afm;
}
#Basic
#Column(name = "Salary", nullable = true, precision = 2)
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
#Basic
#Column(name = "BonusProgram", nullable = true)
public Byte getBonusProgram() {
return bonusProgram;
}
public void setBonusProgram(Byte bonusProgram) {
this.bonusProgram = bonusProgram;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserIsWorkerEntity that = (UserIsWorkerEntity) o;
return Objects.equals(workerId, that.workerId) &&
Objects.equals(userLogName, that.userLogName) &&
Objects.equals(userLogPass, that.userLogPass) &&
Objects.equals(amka, that.amka) &&
Objects.equals(afm, that.afm) &&
Objects.equals(salary, that.salary) &&
Objects.equals(bonusProgram, that.bonusProgram);
}
#Override
public int hashCode() {
return Objects.hash(workerId, userLogName, userLogPass, amka, afm, salary, bonusProgram);
}
#OneToOne
#JoinColumn(name = "WorkerID", referencedColumnName = "UserID", nullable = false)
public UserEntity getUserByWorkerId() {
return userByWorkerId;
}
public void setUserByWorkerId(UserEntity userByWorkerId) {
this.userByWorkerId = userByWorkerId;
}
#ManyToOne
#JoinColumn(name = "Supervisor", referencedColumnName = "WorkerID")
public UserIsWorkerEntity getUserIsWorkerBySupervisor() {
return userIsWorkerBySupervisor;
}
public void setUserIsWorkerBySupervisor(UserIsWorkerEntity userIsWorkerBySupervisor) {
this.userIsWorkerBySupervisor = userIsWorkerBySupervisor;
}
#ManyToOne
#JoinColumn(name = "PermisID", referencedColumnName = "PermisID")
public PermisEntity getPermisByPermisId() {
return permisByPermisId;
}
public void setPermisByPermisId(PermisEntity permisByPermisId) {
this.permisByPermisId = permisByPermisId;
}
}
And here is the Entity, of the table that is related with the previous one:
package Entities;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "user", schema = "walker", catalog = "")
public class UserEntity {
private String userId;
private String name;
private String surname;
private Date birthday;
private UserIsShopkeeperEntity userIsShopkeeperByUserId;
private UserIsWorkerEntity userIsWorkerByUserId;
#Id
#Column(name = "UserID", nullable = false, length = 20)
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Basic
#Column(name = "Name", nullable = true, length = 35)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "Surname", nullable = true, length = 35)
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Basic
#Column(name = "Birthday", nullable = true)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(name, that.name) &&
Objects.equals(surname, that.surname) &&
Objects.equals(birthday, that.birthday);
}
#Override
public int hashCode() {
return Objects.hash(userId, name, surname, birthday);
}
#OneToOne(mappedBy = "userByShopKeeperId")
public UserIsShopkeeperEntity getUserIsShopkeeperByUserId() {
return userIsShopkeeperByUserId;
}
public void setUserIsShopkeeperByUserId(UserIsShopkeeperEntity userIsShopkeeperByUserId) {
this.userIsShopkeeperByUserId = userIsShopkeeperByUserId;
}
#OneToOne(mappedBy = "userByWorkerId")
public UserIsWorkerEntity getUserIsWorkerByUserId() {
return userIsWorkerByUserId;
}
public void setUserIsWorkerByUserId(UserIsWorkerEntity userIsWorkerByUserId) {
this.userIsWorkerByUserId = userIsWorkerByUserId;
}
}
And finally, this is my hibernate.cfg.xml file:
<?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/walker</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="format_sql">true</property>
<property name="show_sql">true</property>
<mapping class="Entities.ActivationEntity"/>
<mapping class="Entities.AutomaticSoftwareEntity"/>
<mapping class="Entities.CanisterEntity"/>
<mapping class="Entities.ChargeEntity"/>
<mapping class="Entities.CityEntity"/>
<mapping class="Entities.ColorVersionEntity"/>
<mapping class="Entities.CompanyEntity"/>
<mapping class="Entities.ComTypeEntity"/>
<mapping class="Entities.ContractEntity"/>
<mapping class="Entities.ContractEventEntity"/>
<mapping class="Entities.CountryEntity"/>
<mapping class="Entities.CustomerEntity"/>
<mapping class="Entities.CustomerHasRequestsEntity"/>
<mapping class="Entities.CustomerHasShopkeepersEntity"/>
<mapping class="Entities.CustomerHasTargetsEntity"/>
<mapping class="Entities.CustomerHasVersionsEntity"/>
<mapping class="Entities.DepartmentEntity"/>
<mapping class="Entities.DispenserTechEntity"/>
<mapping class="Entities.EventEntity"/>
<mapping class="Entities.MachineAgeEntity"/>
<mapping class="Entities.MailEntity"/>
<mapping class="Entities.ModelEntity"/>
<mapping class="Entities.ModelHasPartsEntity"/>
<mapping class="Entities.ModelDispenserEntity"/>
<mapping class="Entities.ModelPartEntity"/>
<mapping class="Entities.ModelRootEntity"/>
<mapping class="Entities.ModelTypeEntity"/>
<mapping class="Entities.MonitorEntity"/>
<mapping class="Entities.MonitorPanelEntity"/>
<mapping class="Entities.ObjectEntity"/>
<mapping class="Entities.ObjectEventEntity"/>
<mapping class="Entities.PartEntity"/>
<mapping class="Entities.PcEntity"/>
<mapping class="Entities.PermisEntity"/>
<mapping class="Entities.PhoneEntity"/>
<mapping class="Entities.PrinterEntity"/>
<mapping class="Entities.PriorityEntity"/>
<mapping class="Entities.PumpEntity"/>
<mapping class="Entities.RegionEntity"/>
<mapping class="Entities.RequestsEntity"/>
<mapping class="Entities.RoleEntity"/>
<mapping class="Entities.SectionEntity"/>
<mapping class="Entities.ShakerEntity"/>
<mapping class="Entities.ShakerTypeEntity"/>
<mapping class="Entities.ShelfEntity"/>
<mapping class="Entities.SpectroEntity"/>
<mapping class="Entities.StatusEntity"/>
<mapping class="Entities.StatusHasStoreEntity"/>
<mapping class="Entities.StoreEntity"/>
<mapping class="Entities.SupplierEntity"/>
<mapping class="Entities.SupplierHasVendorsEntity"/>
<mapping class="Entities.TeamviewerEntity"/>
<mapping class="Entities.UpsEntity"/>
<mapping class="Entities.UserEntity"/>
<mapping class="Entities.UserHasEmailsEntity"/>
<mapping class="Entities.UserHasPhonesEntity"/>
<mapping class="Entities.UserIsShopkeeperEntity"/>
<mapping class="Entities.UserIsWorkerEntity"/>
<mapping class="Entities.VariantEntity"/>
<mapping class="Entities.VendorEntity"/>
<mapping class="Entities.WifiAdapterEntity"/>
<mapping class="Entities.WorkerHasRegionsEntity"/>
<mapping class="Entities.WorkerHasRolesEntity"/>
<mapping class="Entities.WorkerHasSectionsEntity"/>
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Thanks in advance!
The error complains about Object field type for info field in ObjectEntity entity class. Changing to appropriate type will solve the problem.
Also, look at a similar problem.
org.hibernate.MappingException: property mapping has wrong number of columns in ENUM entity

happening " java.lang.ExceptionInInitializerError " Caused by " Unable to build EntityManagerFactory " in JPA project

I want create a web application and use JPA for model layer in MVC for the first time . But I'm having trouble.
The program shows me this error :
Nov 11, 2018 10:56:49 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" java.lang.ExceptionInInitializerError
at model.bl.PersonManager.main(PersonManager.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: MyConnection] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:930)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:72)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at util.JPAProvider.<clinit>(JPAProvider.java:13)
... 6 more
Caused by: org.hibernate.MappingException: Unable to find column with logical name: UID in org.hibernate.mapping.Table(USERS) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:552)
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:257)
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1331)
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:791)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:719)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:668)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1593)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1350)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 11 more
Person class :
package model.entity;
import model.bl.PersonManager;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
//mapping class to table
#Entity (name = "person")
#Table(name = "USERS")
#EntityListeners(value = PersonManager.class)
public class Person implements Serializable
{
#Id // create id and fill auto by sequence in database
#Column(name="UID" ,columnDefinition = "NUMBER" )
#SequenceGenerator(name = "mySeq" , sequenceName = "DB_MYSEQ")
#GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq")
private long uId;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
private List<Pictures> picturesList;
#Basic
#Column (name = "USERNAME" , columnDefinition = "NVARCHAR2(30)" , nullable = false , unique = true)
private String username ;
#Basic
#Column (name = "USER_PASSWORD" , columnDefinition = "NVARCHAR2(32)" , nullable = false , unique = true)
private String password ;
#Basic
#Column (name = "EMAIL" , columnDefinition = "NVARCHAR2(40)" , nullable = false)
private String email;
#Basic
#Column (name = "SEX" , columnDefinition = "NVARCHAR2(20)")
private String sex ;
//--------------------------------------------------------
public Person() { }
public Person(String username, String password, String email, String sex, String userPic) {
this.username = username;
this.password = password;
this.email = email;
this.sex = sex;
this.userPic = userPic;
}
public Person(String username, String password, String email ,String sex, String userPic,List<Pictures> picturesList ) {
this.picturesList = picturesList;
this.sex = sex;
this.userPic = userPic;
this.email = email;
this.password = password;
this.username = username;
}
//--------------------------------------------------------
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setUserPic(String userPic) {
this.userPic = userPic;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setuId(long uId) {this.uId = uId;}
//--------------------------------------------------------
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUserPic() {
return userPic;
}
public String getEmail() {
return email;
}
public String getSex() {
return sex;
}
public long getuId() {return uId;}
}
}
Pictures class :
package model.entity;
import javax.persistence.*;
import java.io.Serializable;
#Entity(name = "picture")
#Table(name = "PICTURE")
public class Pictures implements Serializable
{
#Id // create id and fill auto by sequence in database
#Column(name="PID" ,columnDefinition = "NUMBER" )
#SequenceGenerator(name = "mySeq2" , sequenceName = "DB_MYSEQ2")
#GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq2")
private long pId;
#Basic
#Column (name = "PICADRESS" , columnDefinition = "NVARCHAR2(50)" , nullable = false)
private String picAdress ;
#Basic
#Column (name = "CAPTION" , columnDefinition = "LONG")
private String caption;
#Basic // user picture for profile
#Column (name = "LIKES" , columnDefinition = "NUMBER")
private int likes;
//--------------------------------------------------------
public Pictures(){}
public Pictures( String picAdress, String caption, int likes) {
this.picAdress = picAdress;
this.caption = caption;
this.likes = likes;
}
//--------------------------------------------------------
public void setPid(long pid) {
this.pId = pid;
}
public void setLikes(int likes) {
this.likes = likes;
}
public void setPicAdress(String picAdress) {
this.picAdress = picAdress;
}
public void setCaption(String caption) {
this.caption = caption;
}
//--------------------------------------------------------
public int getLikes() {
return likes;
}
public String getCaption() {
return caption;
}
public String getPicAdress() {
return picAdress;
}
public long getPid() {
return pId;
}
}
my JPA Provider is :
public class JPAProvider {
private static final EntityManagerFactory entityManagerFactory;//instate of session for connect to database
static{
entityManagerFactory = Persistence.createEntityManagerFactory("MyConnection");
}
public static EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}
PersonManager class is :
public class PersonManager {
public static void main(String[] args) {
EntityManager entityManager = JPAProvider.getEntityManagerFactory().createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Person person = new Person("midas" , "midas123" , "aaaaa#gmail.com", "female" ,"female-user.png" );
Pictures pictures = new Pictures("aaa" , "akflkkglhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" ,2);
Pictures pictures2 = new Pictures("nnbnbn" , "affddAlllllllllllllllllllllllllllllllllllll" ,5);
List<Pictures> picturesList =new ArrayList<Pictures>();
picturesList.add(pictures);
picturesList.add(pictures2);
person.setPicturesList(picturesList);
entityManager.persist(person);
entityTransaction.commit();
entityManager.close();
}
}
and persistence.xml :
<persistence-unit name="MyConnection" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.username" value="midas"/>
<property name="hibernate.connection.password" value="midas123"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:orcl"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"></property>
<property name="hibernate.globally_quoted_identifiers" value="true"/>
</properties>
</persistence-unit>
I used the following libraries :
1)hibernate-enverc-4.2.0.final
2)hibernate-jpa-2.0-api-1.0.1-final.jar
3)tomcat library
my JDK version = 1.8.0-172
my IDE = IntellyJ Idea
I use Oracle 11g .
I tried to solve the problem by solving similar questions, but I could not .
for example I checked the following topics that were more similar to my problem :
[Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed
[Getting Exception in thread "main" java.lang.ExceptionInInitializerError Exception
Additional explanation: No tables have been created in the database so far.
Looks like problem is with #JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
referencedColumnName attribute points to the related column in asociated/referenced entity, i.e. column name of the primary key. By default it is primary key of associated entity. You are not required to fill the referencedColumnName if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. primary key column of associated entity).
change that line to #JoinColumn(name = "FK_PERSON") it should work.
For more info about referencedColumnName refer to "What is referencedColumnName used for in JPA?"

Hibernate: New Session without dropping the tables

I am new to Hibernate (implementing since yesterday) and i succesfully created a method, that transfers my Customer Objects to the Database.
After i quit my application and start it again and create a new session (in an other method) based on my hibernate.cfg.xml file with this setting:
<property name="hibernate.hbm2ddl.auto">create</property>
It leads to that point, that all relevant tables, created with Hibernate are being deleted.
So maybe that is a comprehension question, but i think "transparent persistence by hibernate" means also, that my POJO's are persistent beyond the runtime of my application!?
So i read several topics on Stackoverflow and tried it with this setting:
<property name="hibernate.hbm2ddl.auto">update</property>
But this leads to SQL errors:
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
Of course i don't want have duplicates, so i suppose that hibernate doesn't send a SQL Statement referring to an existing object.
It sends a Statement like this:
UPDATE `customer` SET `id`=1,`birthday`='1990-10-05 00:00:00',`forename`='TestCustomer',`gender`='F',`generatedProfitsLastYear`='0',`generatedProfitsTotal`='0',`surename`='A',`gcid`='1'
But i need the same statement, with a
Where `id`=1
at the end.
So basically what i want is, that hibernate doesn't drop all the tables and creates it again when i restart my application and create a new session based on the configuration file. So after i open a new session, i can transfer the Customer Objects stored in the database to POJOs.
Did i understand the concept of hibernate incorrectly or am i making a typical beginners mistake?
Below you will find my Customer Class:
#Entity
#Table(name="CUSTOMER")
public class Customer {
private int id;
private String forename;
private String surname;
private char gender;
private Date birthday;
private double generatedProfitsTotal;
private double generatedProfitsLastYear;
private CustomerGroup assignedTo;
public Customer(int id, String forename, String surname, char gender,
Date birthday) {
super();
this.id = id;
this.forename = forename;
this.surname = surname;
this.gender = gender;
this.birthday = birthday;
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "forename")
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
#Column(name = "surename")
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Column(name = "gender")
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Column(name = "birthday")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
#Column(name = "generatedProfitsTotal")
public double getGeneratedProfitsTotal() {
return generatedProfitsTotal;
}
public void setGeneratedProfitsTotal(double generatedProfitsTotal) {
this.generatedProfitsTotal = generatedProfitsTotal;
}
#Column(name = "generatedProfitsLastYear")
public double getGeneratedProfitsLastYear() {
return generatedProfitsLastYear;
}
public void setGeneratedProfitsLastYear(double generatedProfitsLastYear) {
this.generatedProfitsLastYear = generatedProfitsLastYear;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="gcid", nullable=true, insertable=true, updatable=true)
public CustomerGroup getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(CustomerGroup assignedTo) {
this.assignedTo = assignedTo;
}
}
my hibernate config file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hibernatetesting</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="studyproject.Customer"/>
<mapping class="studyproject.CustomerGroup"/>
<mapping class="studyproject.BonusPackage"/>
</session-factory>
</hibernate-configuration>
Thanks
try session.saveOrUpdate() method where you have used session.save() it will prevent your database from dropping while fetching data use it with hbm2ddl.auto update. it worked for me. hope it helps.
What did you do where the 'duplicate error' occurs? Now I have the hibernate.hbm2ddl.auto configured as yours, but it's okay saving or updating entity in my local.

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

Categories

Resources