Hibernate keeps updating database even when I work with local variables - java

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);
}
}

Related

Hibernate doesn't save entity

I'm really new to hibernate and try to understand how it works. But know I faced with the problem.
First of all, I have such mapping:
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Author() {
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
But then, when I tried to save this entitye with session.save(), hibernate showed me error like
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "author" violates not-null constraint
Failing row contains (null, hello!).
So I decided to notice, why hibernate doesn't increment the id automaticy and recognized that POSTGRESQL doesn't suppert annotation GenerationType.IDENTITY. So I changet it to the GenerationType.SEQUENCE. The error was gone, but entity wasn't saved.
So here's 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:postgresql://localhost:5432/hibernate?useSSL=false
&serverTimezone=UTC</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="connection.username">postgres</property>
<property name="connection.password">4122</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="hibernate.entity.Author"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Here's HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.build();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
return sessionFactoryBuilder.build();
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
And here's the Main.java, where I call the hibernate functions:
public class Main {
public static void main(String[] args) {
try(Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
Author author = new Author();
author.setName("hello!");
session.save(author);
tx.commit();
System.out.println(session.get(Author.class, 1L));
}
}
}
After program execution it prints me null and there is no entity in database:
If you know, what can be the problem, please tell me. I'd really apreciate it!
I think the reason is setter for id missing:
public long setId(long id) {
this.id = id;
}

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

Hibernate H2 database not found

I'm quite new to hibernate so my problem can be obvious to you. I created database in H2 Console with 3 tables (data.mv.db), insert some values and then copied it to my database folder in project path. Now I'm trying to read one of them for tests, but always have error that table not exists. I've tried to add properties to connection url like connection delay or not changing letter to upper case but still the same.
Error:
Caused by: org.h2.jdbc.JdbcSQLException: Tabela "LOGIN_DATA" nie
istnieje Table "LOGIN_DATA" not found; SQL statement: select
login_data0_.ID as ID1_0_, login_data0_.USERNAME as USERNAME2_0_,
login_data0_.PASSWORD as PASSWORD3_0_, login_data0_.FAVOURITE as
FAVOURIT4_0_ from PUBLIC.LOGIN_DATA login_data0_ [42102-192] at
org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179) at
org.h2.message.DbException.get(DbException.java:155) at
org.h2.schema.Schema.getTableOrView(Schema.java:437) at
org.h2.command.Parser.readTableOrView(Parser.java:5371) at
org.h2.command.Parser.readTableFilter(Parser.java:1257) at
org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1896) at
org.h2.command.Parser.parseSelectSimple(Parser.java:2044) at
org.h2.command.Parser.parseSelectSub(Parser.java:1890) at
org.h2.command.Parser.parseSelectUnion(Parser.java:1709) at
org.h2.command.Parser.parseSelect(Parser.java:1697) at
org.h2.command.Parser.parsePrepared(Parser.java:445) at
org.h2.command.Parser.parse(Parser.java:317) at
org.h2.command.Parser.parse(Parser.java:289) at
org.h2.command.Parser.prepareCommand(Parser.java:254) at
org.h2.engine.Session.prepareLocal(Session.java:560) at
org.h2.engine.Session.prepareCommand(Session.java:501) at
org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1201)
at
org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73)
at
org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:289)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:145)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:171)
... 17 more
Hibernate Config:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:file:~/database/data</property>
<property name="connection.username">admin</property>
<property name="connection.password">1234</property>
<property name="hibernate.default_schema">PUBLIC</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="data.Login_data"/>
</session-factory>
</hibernate-configuration>
Login_data class:
#Entity
#Table(name = "LOGIN_DATA")
public class Login_data {
private int id;
private String name;
private String password;
private String values;
public Login_data() {
// this form used by Hibernate
}
public Login_data(int id, String name, String password, String values) {
this.id = id;
this.name = name;
this.password = password;
this.values = values;
}
#Id
#GeneratedValue
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "USERNAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "FAVOURITE")
public String getValues() {
return values;
}
public void setValues(String values) {
this.values = values;
}
}
Main class:
public static void main(String[] args){
Login_data user = new Login_data();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
/*session.beginTransaction();
session.save(user);
session.getTransaction().commit();*/
// now lets pull events from the database and list them
session.beginTransaction();
List result = session.createQuery("from Login_data").list();
for (Login_data event : (List<Login_data>) result) {
System.out.println(event.getName());
}
System.out.print(result);
session.getTransaction().commit();
session.close();
}
I've tried to edit configuration. So I add:
<property name="hibernate.hbm2ddl.auto">update</property>
And make empty database. What is strange is database and table created by Java after opening in H2 Console is not visible. So that can be the problem.
I wanted to put a lot of data, so how to make it not from java to be visible there?
Thanks to #JB Nizet I see my error. I was copying database to project path, where my path "~/database" shows to database in user folder, and I was copying it to project folder so I should use "./database" .
Still if I want to make runnable I would need to use user location to have it rightly working on other machines.

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

Hibernate creating wrong create table statement?

It's my first time configuring hibernate. I've read many tutorials but not sure why this is creating the wrong create table sql statement. I am using PostgreSQL as my database.
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://DBIP:5432/MYDB</property>
<property name="hibernate.connection.username">MYDB</property>
<property name="hibernate.connection.password">MYPASS</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="MYPROJ.model.User"/>
</session-factory>
</hibernate-configuration>
User.java
package MYPROJ.model;
import javax.persistence.*;
#Entity
public class User
{
#Id #GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "username")
private String username;
#Column(name = "age")
private int age;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
Main.java
public class Main
{
public static void main(String[] args)
{
User user = new User();
user.setId(1);
user.setAge(20);
user.setUsername("david");
SessionFactory sessionFactory;
ServiceRegistry serviceRegistry;
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
System.out.println("Done!");
}
}
When I run the program it shows the following SQL statement for creating the table which does not work when I run the program or when I copy pasted it manually
create table User (id int4 not null, age int4, username varchar(255), primary key (id))
What am I doing wrong here?
It turned out that "user" was a reserved keyword in PostgreSQL, changing that fixed the issue.
You can tell hibernate your column name must be escaped to avoid conflicts with the database keywords. To do that, enclose the name between `. Example:
#Column(name="`user`")

Categories

Resources