Hibernate Util Class - java

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

Related

Hibernate keeps updating database even when I work with local variables

I encountered an issue, where the items from my database get deleted at a certain point. It seems like Hibernate updates the database when I'm working with local variables.
Here is my hibernate.cfg.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
" http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- MySQL Configuration -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">dbname</property>
<property name="connection.username">dbusername</property>
<property name="connection.password">dbpassword</property>
<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping class="model.User"/>
<mapping class="model.Admin"/>
<mapping class="model.Student"/>
<mapping class="model.Teacher"/>
<mapping class="model.Classroom"/>
<mapping class="model.Quiz"/>
<mapping class="model.Task"/>
<mapping class="model.Solution"/>
<mapping class="model.CorrectSolution"/>
<mapping class="model.WrongSolution"/>
<mapping class="model.Result"/>
</session-factory>
</hibernate-configuration>
I'll post a few examples of code where items get deleted.
This is my own ComboBox class, I save objects of Quiz class in it and I want to remove every Quiz which has an empty TaskList.
private void removeEmptyQuizzes(List<Quiz> quizList){
for(Quiz q : quizList){
if(q.getTaskList().isEmpty()){
quizList.remove(q);
}
}
setItems(FXCollections.observableArrayList(quizList));
}
What happens is that all Quizzes with empty TaskList get completely deleted from the database, not just from the ComboBox.
My application is a Quiz test game, so here's another example. I load the tasks into a List<Task> and then I remove the
private void fillTaskList(){
taskList = SelectedQuiz.getQuiz().getTaskList();
taskNumber = taskList.size();
}
private void loadTask(){
if(!taskList.isEmpty()) {
int taskIndex = new Random().nextInt(taskList.size());
task = taskList.get(taskIndex);
// extra stuff for my quiz - not relevant to the question
/*view.getLbQuestion().setText(task.getQuestion());
List<AnswerBox> answerBoxList = createAnswerBoxList();
List<Solution> solutionList = createSolutionList(task);
int bound = answerBoxList.size();
for(AnswerBox box : answerBoxList){
int index = (new Random().nextInt(bound) + 1) - 1;
Solution sol = solutionList.get(index);
box.setSolution(sol);
solutionList.remove(sol);
bound--;
}*/
taskList.remove(taskList.get(taskIndex));
}
else {
Student student = (Student) LoggedInUtil.getLoggedInUser();
Quiz quiz = SelectedQuiz.getQuiz();
Result result = new Result(correctAnswers, wrongAnswers, student, quiz.getName());
new ResultDao().insertResult(result);
rootView.setEndMiddle(taskNumber, correctAnswers, wrongAnswers);
}
}
Now, I have Tasks saved in the database. However, they all get deleted when I call this new ResultDao().insertResult(result); function. I tried sysouting Quiz.getTaskList.size() in the final else (before saving the Result) and it indeed was 0 and Hibernate updated it.
Now, why does Hibernate automatically update my variables? I have specific Dao classes to work with database, but I don't call them in these cases.
I appreciate all answers, thank you.
EDIT: added InsertResult() method on request
public void insertResult(Result r) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(r);
transaction.commit();
}
EDIT2: added mapping for Result class
#Entity
public class Result {
private int result_id, correctAnswers, wrongAnswers;
private Student student;
private SimpleStringProperty quizName = new SimpleStringProperty();
public Result() {
}
public Result(int correctAnswers, int wrongAnswers, Student student, String quizName) {
this.correctAnswers = correctAnswers;
this.wrongAnswers = wrongAnswers;
this.student = student;
this.quizName.set(quizName);
}
#Column(nullable = false)
public int getCorrectAnswers() {
return correctAnswers;
}
public void setCorrectAnswers(int correctAnswers) {
this.correctAnswers = correctAnswers;
}
#Column(nullable = false)
public int getWrongAnswers() {
return wrongAnswers;
}
public void setWrongAnswers(int wrongAnswers) {
this.wrongAnswers = wrongAnswers;
}
#Id
#GenericGenerator(name="id" , strategy="increment")
#GeneratedValue(generator="id")
public int getResult_id() {
return result_id;
}
public void setResult_id(int result_id) {
this.result_id = result_id;
}
#ManyToOne(targetEntity = Student.class)
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Column(nullable = false)
public String getQuizName() {
return quizName.get();
}
public SimpleStringProperty quizNameProperty() {
return quizName;
}
public void setQuizName(String quizName) {
this.quizName.set(quizName);
}
#Transient
public SimpleStringProperty studentWithClassProperty(){
String studentWithClass = getStudent().getName() + getStudent().getSurname() + " - " + getStudent().getClassroom().toString();
return new SimpleStringProperty(studentWithClass);
}
}

Can't create entity with Hibernate. SQLGrammarException

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")

Hibernate session.get() shows null

Although I read session.get null problems on stackoverflow and tried to do what they suggested, my problem seems to continue.
SessionFactory mysessionfactory = new Configuration().configure().buildSessionFactory();
Session mysession = mysessionfactory.openSession();
mysession.beginTransaction();
Myperson person3 = (Myperson) mysession.get(Myperson.class, 3);
System.out.println("there you go : "+person3.getName());
As simple as it seems, i am just trying to retrieve data from database. Let me show you the database.
As you can see above , the data i like to retrieve has a name !
This is what i get, NOTHING !
And finally , i run the code with debug mode and i hope you'll understand the problem and suggest a solution.
i am in a conflict here, my database shows that data which has UserId of 3 has a name but why can't i see it in my output ?
EDIT : Here is my hibernate xml file as you requested.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.pool.size">1</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/myhibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
000003
</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping class="org.emreverim.com.Myperson"/>
<mapping class="org.emreverim.com.Vehicle" />
<mapping class="org.emreverim.com.FourWheeler" />
<mapping class="org.emreverim.com.TwoWheeler" />
</session-factory>
</hibernate-configuration>
EDIT 2 : here is myperson class as you requested.
#Entity
public class Myperson {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int userID;
private String name;
#OneToMany(cascade=CascadeType.PERSIST)
private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
public Collection<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(Collection<Vehicle> vehicle) {
this.vehicle = vehicle;
}
#Lob
private String description;
#Temporal (TemporalType.DATE)
private Date joinedDate;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getJoinedDate() {
return joinedDate;
}
public void setJoinedDate(Date joinedDate) {
this.joinedDate = joinedDate;
}
public int getUserID() {
return userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setUserID(int userID){
this.userID = userID;
}
}
I think the problem here is caused by the fact that Hibernate Session.get() method expects a Seriliazable id object, which is not provided in your case here mysession.get(Myperson.class, 3) .
Because the given value 3 here is of primitive type int which contains only the value and isn't serialized so you have to use new Integer() method in order to pass an Integer serializable object or new Long() to pass a Long serializable object to the get() method, so just change:
Myperson person3 = (Myperson) mysession.get(Myperson.class, 3);
To:
Myperson person3 = (Myperson) mysession.get(Myperson.class, new Integer(3));
Or:
Myperson person3 = (Myperson) mysession.get(Myperson.class, new Long(3));
We happened to see the solution, my database has been configured as utf-16 while it should have been utf-8. so its just as simple as that. i gave thumps up for all answers, thanks for all of your concerns.
In your entity map you forgot to add the annotations #column attributes to the field and #table to link it to the table.
Example:
#Column(name="description")
private String description;
Check this example for the annotations http://archive.oreilly.com/pub/a/onjava/2007/02/08/an-introduction-to-hibernate-3-annotations.html?page=2

Getting the following error org.hibernate.MappingException: No Dialect mapping for JDBC type: -1

I am getting following exception at query.can you please tell mw whats wrong is in my code?
org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(Custom Loader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
at com.bdisys.promorphics.dao.impl.BlogDaoImpl.getTopBlogsQuesByDate(BlogDaoImpl.java:126)
at org.apache.jsp.Mydetails_jsp._jspService(Mydetails_jsp.java:935)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Blog.java :
#SuppressWarnings("serial")
#Entity
#Table(name="blog")
public class Blog extends BaseDomain {
#Column(name="blog_title")
private String blogTitle;
#Column(name="blog_text",columnDefinition="TEXT")
private String blogText;
#Enumerated(EnumType.STRING)
#Column(name="blog_status")
private Status blogStatus;
#OneToOne
#JoinColumn(name="created_by", nullable=false)
private User createdBy;
#OneToOne
#JoinColumn(name="blog_category", nullable=false)
private BlogCategory blogCategory;
#Temporal(TemporalType.DATE)
#Column(name="created_date")
private Date createdDate;
#Column(name="likes")
private Long likes;
#Column(name="uploads")
private String uploads;
#Column(name="youtube_link")
private String youTubeLik;
#Column(name="moderator_comment")
private String moderatorComment;
#Lob
#Column(name="blog_description")
private String blog_desc;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public String getBlog_desc() {
return blog_desc;
}
public void setBlog_desc(String blog_desc) {
this.blog_desc = blog_desc;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogText() {
return blogText;
}
public void setBlogText(String blogText) {
this.blogText = blogText;
}
public Status getBlogStatus() {
return blogStatus;
}
public void setBlogStatus(Status blogStatus) {
this.blogStatus = blogStatus;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public BlogCategory getBlogCategory() {
return blogCategory;
}
public void setBlogCategory(BlogCategory blogCategory) {
this.blogCategory = blogCategory;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Long getLikes() {
return likes;
}
public void setLikes(Long likes) {
this.likes = likes;
}
public String getUploads() {
return uploads;
}
public void setUploads(String uploads) {
this.uploads = uploads;
}
public String getYouTubeLik() {
return youTubeLik;
}
public void setYouTubeLik(String youTubeLik) {
this.youTubeLik = youTubeLik;
}
public String getModeratorComment() {
return moderatorComment;
}
public void setModeratorComment(String moderatorComment) {
this.moderatorComment = moderatorComment;
}
}
Askquestions.java :
#SuppressWarnings("serial")
#Entity
#Table(name="askquestions")
public class Askquestions extends BaseDomain {
#Column(length = 100, name = "id_subscribers")
private String idSubscribers;
#Column(length = 100, name = "is_anonymous")
private String isAnonymous;
#Column(length = 100, name = "display_name")
private String displayName;
#Temporal(TemporalType.DATE)
#Column(length = 100, name = "created_on")
private Date createdQuesOn;
#Lob
#Column(name = "ask_question")
private String askQuestion;
#Column(length = 100, name = "ask_to_whom")
private String askToWhom;
#Lob
#Column(name="question_of_day")
private String questionOfDay;
#ManyToOne
#JoinColumn(name="ask_category")
private Askcategory askcategory;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public Askcategory getAskcategory() {
return askcategory;
}
public void setAskcategory(Askcategory askcategory) {
this.askcategory = askcategory;
}
public String getQuestionOfDay() {
return questionOfDay;
}
public void setQuestionOfDay(String questionOfDay) {
this.questionOfDay = questionOfDay;
}
public String getIdSubscribers() {
return idSubscribers;
}
public void setIdSubscribers(String idSubscribers) {
this.idSubscribers = idSubscribers;
}
public String getIsAnonymous() {
return isAnonymous;
}
public void setIsAnonymous(String isAnonymous) {
this.isAnonymous = isAnonymous;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAskQuestion() {
return askQuestion;
}
public void setAskQuestion(String askQuestion) {
this.askQuestion = askQuestion;
}
public String getAskToWhom() {
return askToWhom;
}
public void setAskToWhom(String askToWhom) {
this.askToWhom = askToWhom;
}
public Date getCreatedQuesOn() {
return createdQuesOn;
}
public void setCreatedQuesOn(Date createdQuesOn) {
this.createdQuesOn = createdQuesOn;
}
}
BlogDaoimpl Method:this query is not getting executed while other small queries are getting executed.why is it happening????
String sql = " select title , date from (select blog_title as title ,created_date as date from blog union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
hibrnate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- <property name="hibernate.connection.password">websitebdi</property>
<property name="hibernate.connection.url">jdbc:mysql://184.172.182.251:3306/bdiwebsite</property>
<property name="hibernate.connection.username">bdiwebsite</property> -->
<property name="hibernate.connection.password">MAYbdiSYS2008</property>
<property name="hibernate.connection.url">jdbc:mysql://115.119.114.10:3306/bdisystems</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- The maximum number of connections -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- The minimum number of connections -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- Get a connection timeout , If you exceed this time , Throws an exception, in milliseconds -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- The maximum number of PreparedStatement -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Every 120 seconds checking connection idle connection in the pool, the unit is in seconds -->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- When connection pooling connections inside out, look at the new C3P0 get the number of connections -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Always verify the connection -->
<property name="hibernate.c3p0.validate">true</property>
<!--
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">0</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.timeout">100</property>
-->
<!-- Mapping Classes -->
<mapping class="com.bdisys.promorphics.domain.BlogCategory"/>
<mapping class="com.bdisys.promorphics.domain.Blog"/>
<mapping class="com.bdisys.promorphics.domain.Career"/>
<mapping class="com.bdisys.promorphics.domain.Partners"/>
<mapping class="com.bdisys.promorphics.domain.Askcategory"/>
<mapping class="com.bdisys.promorphics.domain.Askquestions"/>
<mapping class="com.bdisys.promorphics.domain.Askanswers"/>
</session-factory>
</hibernate-configuration>
Create a custom Dialect (extending MySQLDialect) and in your constructor add
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
public class MySQLDialect extends MySQLDialect {
public AGOSQLServerDialect() {
super();
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
}
}
Remember to change dialect class into Hibernate config file
<property name="hibernate.dialect">path.to.YourDialect</property>

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