Spring hibernate application One to Many relationship 404 - java

I am trying to build an app that has to objects, book and review, a book can have multiple reviews.
I could see the list of books, but when I entered the book page I could see the title and other attributes of the book but not the attributes of the reviews.
Now i modified the code and i get a 404 error with the warning:
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
I want to mention that i don't have Set variable and method implemented in Review class.
I am using annotation and no xml file in my implementation, please help me
Review.java
#Entity
#Table(name = "REVIEW")
public class Review {
#Id
#GeneratedValue
#Column(name = "ID")
private int id;
#Column(name = "R_DATE")
private Date r_date;
#Column(name = "R_AUTHOR")
private String r_author;
#Column(name = "R_TEXT")
private String r_text;
#Column(name = "R_RATING")
private int r_rating;
#Column(name = "R_BOOKID")
#JoinColumn(name = "BOOKID", nullable = false)
private int r_bookid;
#ManyToOne
private Book book;
public Review(String author, String text, Date date, int rating, int bookid, Book book)
{
super();
this.r_author = author;
this.r_text = text;
this.r_date = date;
this.r_rating = rating;
this.r_bookid = bookid;
this.book= book;
}
...
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Book.java
#Entity
#Table(name = "BOOK")
public class Book {
#Id
#GeneratedValue
#Column(name = "BOOKID")
private int bookId;
#Column(name = "BOOKRATING")
private int bookRating;
#Column(name = "BOOKCATEGORY")
private String bookCategory;
#Column(name = "BOOKAUTHOR")
private String bookAuthor;
#Column(name = "BOOKTITLE")
private String bookTitle;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Review> review = new HashSet<Review>(0);
public Book(){
}
public Book(String title)
{
this.bookTitle = title;
}
...
public Set<Review> getReviews() {
return review;
}
public void setReviews(Set<Review> review) {
this.review = review;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
The server log:
INFO: Refreshing WebApplicationContext for namespace 'SpringDispatcher-servlet': startup date [Mon May 04 17:01:08 EEST 2015]; root of context hierarchy
May 04, 2015 5:01:08 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.bookr.app.config.ApplicationContextConfig]
May 04, 2015 5:01:09 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 04, 2015 5:01:09 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 04, 2015 5:01:09 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 04, 2015 5:01:09 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 04, 2015 5:01:10 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 04, 2015 5:01:10 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 04, 2015 5:01:10 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
May 04, 2015 5:01:10 PM org.hibernate.tuple.PojoInstantiator <init>
INFO: HHH000182: No default (no-argument) constructor for class: com.bookr.app.model.Review (class must be instantiated by Interceptor)
May 04, 2015 5:01:11 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp2.BasicDataSource#3f0938ef] of Hibernate SessionFactory for HibernateTransactionManager
May 04, 2015 5:01:11 PM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'SpringDispatcher': initialization completed in 2577 ms
May 04, 2015 5:01:11 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/app] is completed
May 04, 2015 5:01:11 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
May 04, 2015 5:01:12 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/app/] in DispatcherServlet with name 'SpringDispatcher'
The controller
package com.bookr.app.controller;
import com.bookr.app.dao.BookDAO;
import com.bookr.app.dao.ReviewDAO;
import com.bookr.app.model.Book;
import com.bookr.app.model.Review;
/**
* Handles requests for the application home page.
*/
#RestController
#RequestMapping("/app")
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private BookDAO bookDao;
#Autowired
private ReviewDAO reviewDao;
#RequestMapping(value = "/")
public ModelAndView book(Locale locale)
{
List<Book> listBook = bookDao.list();
ModelAndView model = new ModelAndView("book");
model.addObject("bookList", listBook);
logger.info("Welcome home! The client locale is {}.", locale , "and the books will be listed");
return model;
}
#RequestMapping(value = "/book", method = RequestMethod.GET)
public ModelAndView viewBook(HttpServletRequest request) {
int bookId = Integer.parseInt(request.getParameter("id"));
Book book = bookDao.get(bookId);
Set<Review> review = book.getReviews();
ModelAndView model = new ModelAndView("viewBook");
model.addObject("book", book);
model.addObject("review", review);
return model;
}
}
Thank you very much

Related

How to write Joins using CriteriaUpdate?

I would like to request please help me to find out solution for updating the foreign key value in other table.
for example:-
If we taken Device Table
columns are :- devicename
deviceId
displayname
userId
roomId
isDeleted
other table is Rooms Table
columns are :- roomName
roomId
roomType
isDeleted
Hear it is looking like one-to-many relationship.
i.e., one room will contain many devices.
In the above two tables roomId is primary key in Rooms Table and roomId is forgin key in Device Table.
So, Hear what we want is we have to update the roomId in DeviceTable.
I tried but, I cant able to find the solution for this, I request you guys' please help me for this solution.
the database tables will be like
Room Table(room_table)
room_id room_name room_type
1 ROOM1 ROOM_TYPE1
2 ROOM2 ROOM_TYPE2
Device Table like(device_table)
device_id device_name display_name room_id
1 DEVICE1 DISPLAY1 1
2 DEVICE2 DISPLAY2 2
I hope you guys understand the above tables.
So, now Coming to my required task is:-
I want to update roomId in device table i.e., for DEVICE2 we have to update from roomId 1 to roomId 2 AS SHOWN IN BELOW.
Device Table like(device_table)
device_id device_name display_name room_id
1 DEVICE1 DISPLAY1 1
2 DEVICE2 DISPLAY2 2
for this I wrote java code like:-
#Entity
#Table(name = "device_table")
public class Device {
#Id
#Column(name = "device_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int deviceId;
#Column(name = "device_name")
private String deviceName;
#Column(name = "display_name")
private String dispalyName;
#ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
//private List<Room> roomList = new ArrayList<>();
#JoinColumn(name = "ROOM_ID")
private Room roomList;
//setters & getters
}
#Entity
#Table(name = "room_table")
public class Room {
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int roomId;
#Column(name = "room_name")
private String roomName;
#Column(name = "room_type")
private String roomType;
#OneToMany(mappedBy="roomList")
private Collection<Device> deviceList = new ArrayList<>();
//setters & getters
}
For updating I tried code like below.
public class SaveDataClientTest {
public static void main(String[] args) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
session.beginTransaction();
CriteriaBuilder userBuilder = session.getCriteriaBuilder();
CriteriaUpdate<Device> deviceUpdate = userBuilder.createCriteriaUpdate(Device.class);
Root<Device> deviceUpdateRoot = deviceUpdate.from(Device.class);
Subquery<Device> deviceSubquery = deviceUpdate.subquery(Device.class);
Root<Device> roomRoot = deviceSubquery.from(Device.class);
Join<Device, Room> join = roomRoot.join("roomList", JoinType.LEFT);
deviceUpdate.set(deviceUpdateRoot.get("dispalyName"), "DISPLAY12345");
deviceUpdate.set(join.get("roomId"), 2);
deviceUpdate.where(userBuilder.equal(deviceUpdateRoot.get("deviceName"), "DEVICE2"));
int returnValue = session.createQuery(deviceUpdate).executeUpdate();
System.out.println(returnValue);
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
I am getting error like
Oct 01, 2020 8:00:03 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Oct 01, 2020 8:00:03 PM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: Invalid path: 'generatedAlias1.roomId'
Oct 01, 2020 8:00:03 PM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: Invalid path: 'generatedAlias1.roomId'
Invalid path: 'generatedAlias1.roomId'
at org.hibernate.hql.internal.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:111)
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:214)
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:1038)
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:1026)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.assignment(HqlSqlBaseWalker.java:1054)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.setClause(HqlSqlBaseWalker.java:765)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.updateStatement(HqlSqlBaseWalker.java:381)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:269)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3324)
at org.hibernate.query.criteria.internal.AbstractManipulationCriteriaQuery$1.buildCompiledQuery(AbstractManipulationCriteriaQuery.java:112)
at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:127)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3628)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:203)
at com.infotech.client.SaveDataClientTest.main(SaveDataClientTest.java:54)
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.roomId' [update com.infotech.entities.Device as generatedAlias0 set generatedAlias0.dispalyName = :param0, generatedAlias1.roomId = 2 where generatedAlias0.deviceName=:param1]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3324)
at org.hibernate.query.criteria.internal.AbstractManipulationCriteriaQuery$1.buildCompiledQuery(AbstractManipulationCriteriaQuery.java:112)
at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:127)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3628)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:203)
at com.infotech.client.SaveDataClientTest.main(SaveDataClientTest.java:54)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.roomId' [update com.infotech.entities.Device as generatedAlias0 set generatedAlias0.dispalyName = :param0, generatedAlias1.roomId = 2 where generatedAlias0.deviceName=:param1]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:91)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 6 more
will you please help me to solve this issue.
Thanks.
Have you tried the following?
CriteriaUpdate<Device> deviceUpdate = userBuilder.createCriteriaUpdate(Device.class);
Root<Device> deviceUpdateRoot = deviceUpdate.from(Device.class);
deviceUpdate.set(deviceUpdateRoot.get("dispalyName"), "DISPLAY12345");
deviceUpdate.set(deviceUpdateRoot.get("roomList").get("roomId"), 2);
deviceUpdate.where(userBuilder.equal(deviceUpdateRoot.get("deviceName"), "DEVICE2"));
int returnValue = session.createQuery(deviceUpdate).executeUpdate();
or this?
CriteriaUpdate<Device> deviceUpdate = userBuilder.createCriteriaUpdate(Device.class);
Root<Device> deviceUpdateRoot = deviceUpdate.from(Device.class);
deviceUpdate.set(deviceUpdateRoot.get("dispalyName"), "DISPLAY12345");
deviceUpdate.set(deviceUpdateRoot.get("roomList"), session.getReference(Room.class, 2));
deviceUpdate.where(userBuilder.equal(deviceUpdateRoot.get("deviceName"), "DEVICE2"));
int returnValue = session.createQuery(deviceUpdate).executeUpdate();

How to get dependent objects

I'm trying to get the accounts existing in a bank, but the list is empty even though the link between the two exist in the database.
Knowing that the interaction between the database and my program works fine, except that bank.getAccounts() returns an empty list.
here is my code.
What i'm trying to do is:
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save();
Account c = new account();
c.setBalance(10);
c.setBank(bank);
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save();
for(account c : bank.getAccounts())
System.out.println("account n°: " + c.getId() + ", balance: " + c.getBalance());
}
}
The Bank class is:
#Entity
#Table(name = "BANK")
public class Bank implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8199961750065782869L;
static private BankDAO dao;
private long id;
private String name;
private String street;
private String pc;
private Set<Account> accounts;
public Bank() {
super();
this.accounts = new HashSet<>();
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
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 getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPc() {
return pc;
}
public void setPc(String pc) {
this.pc = pc;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy="bank")
public Set<Account> getAccounts() {
return accounts;
}
public void setAccounts(Set<Account> accounts) {
this.accounts = accounts;
}
// Equals and hashCode implementations deleted
#Transient
private BankDAO getDao() {
if(Bank.dao == null)
dao = BankDAO.getDAO();
return Bank.dao;
}
public long save() {
Bank.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Bank.dao = this.getDao();
return dao.delete(this);
}
}
The Accounts class code:
#Entity
#Table(name = "Account")
public class Account implements Serializable{
private static final long serialVersionUID = 7224745445343369682L;
static private AccountDAO dao;
public long id;
public int balance;
public Bank bank;
public Account() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="bank_id", nullable=false)
#Id
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
#Transient
private AccountDAO getDao() {
if(Account.dao == null)
dao = AccountDAO.getDAO();
return Account.dao;
}
/*
* save the state of the object: save or update
* #return: the id of the object
*/
public long save() {
Account.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Account.dao = this.getDao();
return dao.delete(this);
}
}
Log is:
Feb 13, 2018 11:38:54 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
Feb 13, 2018 11:38:54 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 13, 2018 11:38:54 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Feb 13, 2018 11:38:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernateDataBase]
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Feb 13, 2018 11:38:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Feb 13, 2018 11:38:55 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#67080771
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000038: Composite-id class does not override equals(): business.Account
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000039: Composite-id class does not override hashCode(): business.Account
Hibernate: alter table ACCOUNT drop constraint FKc0nxjvf82u84r0b01m367tss3Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#10650953] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists BANK cascade
Hibernate: drop table if exists ACCOUNT cascade
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start 1 increment 1
Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#7db82169] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table BANK (id int8 not null, pc varchar(255), name varchar(255), street varchar(255), primary key (id))
Hibernate: create table ACCOUNT (id int8 not null, balance int4 not null, bank_id int8 not null, primary key (id, bank_id))
Hibernate: alter table ACCOUNT add constraint FKc0nxjvf82u84r0b01m367tss3 foreign key (bank_id) references BANK
Feb 13, 2018 11:38:56 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#3276732'
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into BANK (pc, name, street, id) values (?, ?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save(); -- checkpoint 1
Account c = new account();
c.setBalance(10);
c.setBank(bank); -- checkpoint 2
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save(); -- checkpoint 3
It wont work that way as as you can see # checkpioint 1 you have you Bank object and nothing will change its state. I gues you would like to Bank->account poulate by checkpoint 2 and 3 but this is not going to happen.
What you have to do is to put that relations manually by simply
bank.getAccounts().add(c1);
However in order to relations to work like you would expect (as bank is already initialized so no lazy fetch will occure), you need to actually fetch your bank again via eg query. Then, newly returned bank will have unitialized collections proxies and will indeed perform additional select (if not eager fetch specified) to get collections of accounts associated with that bank.
I found the problem.
i was using find(id) method to fetch the bank from the database, when i use load(id) or get(id) it works fine.
Best regards.

Hibernate Table not found, MappingException and AssertionException

I tried to map an existing Postgresql Database with Hibernate and it already worked while I didn't add Inheritances per Subclass to Hibernate
This is the superclass
#Entity
#Table(name = "place", schema = "public", catalog = "dbp")
#Inheritance(strategy = InheritanceType.JOINED)
public class PlaceEntity {
private long id;
private String name;
private String url;
// private CityEntity cityById;
private ContinentEntity continentById;
private CountryEntity countryById;
And this is the subclass
#Entity
#Table(name = "city", schema = "public", catalog = "dbp")
#PrimaryKeyJoinColumn(name = "cityid", referencedColumnName = "id")
public class CityEntity extends PlaceEntity{ //WHEN I ADD extends PlaceEntity , THE ERROR OCCURES
private Long cityid;
private Long ispartof;
//private PlaceEntity placeByCityid;
private CountryEntity countryByIspartof;
private Collection<PersonEntity> peopleByCityid;
private Collection<UniversityEntity> universitiesByCityid;
Then Intellij throughs the following exception:
INFO: HHH000270: Type registration [java.util.UUID] overrides previous :org.hibernate.type.UUIDBinaryType#63a12c68
Sep 25, 2017 6:56:11 PM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table dbprak24.public.place not found
Sep 25, 2017 6:56:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/dbprak24]
java.lang.ExceptionInInitializerError
at Main.<clinit>(Main.java:22)
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:297)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Main.<clinit>(Main.java:20)
Caused by: org.hibernate.AssertionFailure: Table dbprak24.public.place not found
at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5231)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 7 more
Exception in thread "main"
Process finished with exit code 1
I already searched for related problems but couldn't find any solution.
I'd be very glad if anyone could help me :)
Always when i delete
extends PlaceEntity
it runs smoothly and it maps als Tables, place included.
I already invested several days in that problem ^^
Sorry for the strange english, it's not my foreign language :)
Nice evening fellows
Eisenbahnplatte
I have faced the same issue (or something very similiar).
Hibernate 5.2.17.Final + PostgreSQL + Inheritance.JOINED.
Solved it by removing "catalog" attribute from mapping. Try to replace
#Table(name = "place", schema = "public", catalog = "dbp")
with
#Table(name = "place", schema = "public")
Hope this helps.

Estado HTTP 500 - Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement

I am using Spring with hibernate, firebird when i run as application i´ve got this error. If i connected in mysql it works ok. Wheres is the wrong? Thx very much.
It´s a Local server accounting Software Desktop and I need this data for export another format (I'm sorry my English Learning).
causa raíz
org.hibernate.exception.SQLGrammarException: could not prepare statement
org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:188)
org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1858)
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: create table HT_empresas (CLAVE numeric(18,0) not null, hib_sess_id CHAR(36))
oct 23, 2014 2:58:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
Información: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.atorresbr.springapp.EmpresasController.list(org.springframework.ui.Model)
oct 23, 2014 2:58:27 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
Información: Using DataSource [org.apache.commons.dbcp.BasicDataSource#1e3ff47] of Hibernate SessionFactory for HibernateTransactionManager
oct 23, 2014 2:58:27 PM org.springframework.web.servlet.FrameworkServlet initServletBean
Información: FrameworkServlet 'apliconta2web': initialization completed in 3840 ms
oct 23, 2014 2:58:27 PM org.apache.coyote.AbstractProtocol start
Información: Starting ProtocolHandler ["http-bio-8080"]
oct 23, 2014 2:58:27 PM org.apache.coyote.AbstractProtocol start
Información: Starting ProtocolHandler ["ajp-bio-8009"]
oct 23, 2014 2:58:27 PM org.apache.catalina.startup.Catalina start
Información: Server startup in 7945 ms
Hibernate: select empresas0_.CLAVE as CLAVE1_0_, empresas0_.ACT_CONTRASE as ACT2_0_, empresas0_.ADMON as ADMON3_0_, empresas0_.BALANCE as BALANCE4_0_, empresas0_.BALANCE_UE as BALANCE5_0_, empresas0_.COBROS as COBROS6_0_, empresas0_.CODPAIS as CODPAIS7_0_, empresas0_.CODPOSTAL as CODPOSTA8_0_, empresas0_.CONTACTO as CONTACTO9_0_, empresas0_.CONTRASE as CONTRAS10_0_, empresas0_.COOPERA as COOPERA11_0_, empresas0_.CORREO as CORREO12_0_, empresas0_.CRITERIOCAJA as CRITERI13_0_, empresas0_.DNICIF as DNICIF14_0_, empresas0_.DOC3W_AUTOGESTION as DOC15_0_, empresas0_.DOC3W_REFURL as DOC16_0_, empresas0_.EJERCICIO as EJERCIC17_0_, empresas0_.E_RETEN as E18_0_, empresas0_.FAX as FAX19_0_, empresas0_.FECHAFIN as FECHAFI20_0_, empresas0_.FECHAINI as FECHAIN21_0_, empresas0_.FECHA_BAJA as FECHA22_0_, empresas0_.FOLIO_R as FOLIO23_0_, empresas0_.GES_DOCU as GES24_0_, empresas0_.GES_PROYECTOS as GES25_0_, empresas0_.HOJA_R as HOJA26_0_, empresas0_.IGIC_IVA as IGIC27_0_, empresas0_.ILOGO as ILOGO28_0_, empresas0_.INUMERO as INUMERO29_0_, empresas0_.LIBRO_R as LIBRO30_0_, empresas0_.MOVILCONTACTO as MOVILCO31_0_, empresas0_.MUNICIPIO as MUNICIP32_0_, empresas0_.NIVEL as NIVEL33_0_, empresas0_.NOMBRE as NOMBRE34_0_, empresas0_.NUMERO as NUMERO35_0_, empresas0_.OBSERVACIONES as OBSERVA36_0_, empresas0_.OCUPADO as OCUPADO37_0_, empresas0_.OTROS_R as OTROS38_0_, empresas0_.PAG_ASIEN as PAG39_0_, empresas0_.PISO as PISO40_0_, empresas0_.PROVINCIA as PROVINC41_0_, empresas0_.PUERTA as PUERTA42_0_, empresas0_.REGCOMPRAS as REGCOMP43_0_, empresas0_.REGMER as REGMER44_0_, empresas0_.REGVENTAS as REGVENT45_0_, empresas0_.SECCION_R as SECCION46_0_, empresas0_.SIGLA as SIGLA47_0_, empresas0_.SUBC_DESP1 as SUBC48_0_, empresas0_.SUBC_DESP2 as SUBC49_0_, empresas0_.SUBC_DESP3 as SUBC50_0_, empresas0_.SUBC_DESP4 as SUBC51_0_, empresas0_.SUBC_DESP7 as SUBC52_0_, empresas0_.SUBC_DESPC1 as SUBC53_0_, empresas0_.SUBC_DESPI1 as SUBC54_0_, empresas0_.SUBC_DESPI2 as SUBC55_0_, empresas0_.SUBC_DESPI3 as SUBC56_0_, empresas0_.SUBC_DESPI4 as SUBC57_0_, empresas0_.SUBC_DESPI5 as SUBC58_0_, empresas0_.SUBC_DESPI6 as SUBC59_0_, empresas0_.SUB_TYPE as SUB60_0_, empresas0_.TELEFONO as TELEFON61_0_, empresas0_.TELEFONO_CONT as TELEFON62_0_, empresas0_.TIPO_EMP as TIPO63_0_, empresas0_.TIPO_R as TIPO64_0_, empresas0_.TOMO_R as TOMO65_0_, empresas0_.VIAPUBLICA as VIAPUBL66_0_, empresas0_.WEB as WEB67_0_, empresas0_.WEBCONTACTO as WEBCONT68_0_ from empresas empresas0_
oct 23, 2014 2:58:29 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 335544569, SQLState: 42000
oct 23, 2014 2:58:29 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: GDS Exception. 335544569. Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 2122
SUB_TYPE
oct 23, 2014 2:58:29 PM org.apache.catalina.core.StandardWrapperValve invoke
Grave: El Servlet.service() para el servlet [apliconta2web] en el contexto con ruta [/Apliconta2Web] lanzó la excepción [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement] con causa raíz
org.firebirdsql.gds.GDSException: Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 2122
SUB_TYPE
at org.firebirdsql.gds.impl.wire.AbstractJavaGDSImpl.readStatusVector(AbstractJavaGDSImpl.java:2092)
at org.firebirdsql.gds.impl.wire.AbstractJavaGDSImpl.receiveResponse(AbstractJavaGDSImpl.java:2042)
at org.firebirdsql.gds.impl.wire.AbstractJavaGDSImpl.iscDsqlPrepare(AbstractJavaGDSImpl.java:1465)
at org.firebirdsql.gds.impl.GDSHelper.prepareStatement(GDSHelper.java:190)
at org.firebirdsql.jdbc.AbstractStatement.prepareFixedStatement(AbstractStatement.java:1441)
at org.firebirdsql.jdbc.AbstractPreparedStatement.prepareFixedStatement(AbstractPreparedStatement.java:1285)
at org.firebirdsql.jdbc.AbstractPreparedStatement.<init>(AbstractPreparedStatement.java:135)
at org.firebirdsql.jdbc.FBPreparedStatement.<init>(FBPreparedStatement.java:40)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.firebirdsql.jdbc.FBStatementFactory.createPreparedStatement(FBStatementFactory.java:89)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:1187)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:942)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:896)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:324)
at org.apache.commons.dbcp.DelegatingConnection.prepareStatement(DelegatingConnection.java:281)
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:313)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1858)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1835)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1815)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2522)
at org.hibernate.loader.Loader.doList(Loader.java:2508)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
at org.hibernate.loader.Loader.list(Loader.java:2333)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at com.atorresbr.springapp.EmpresasDAOImpl.findAll(EmpresasDAOImpl.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.Nativ
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Scans the classpath of this application for #Components #Service #Repository to deploy as
beans -->
<context:component-scan base-package="com.atorresbr.springapp" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
p:validationQuery="${jdbc.validationQuery}" />
<!--
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/pizzashop"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean> -->
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.atorresbr.springapp</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
jdbc.propierties
jdbc.driverClassName= org.firebirdsql.jdbc.FBDriver
jdbc.dialect=org.hibernate.dialect.FirebirdDialect
jdbc.databaseurl=jdbc:firebirdsql:PROSYTH-PC/3050:C:/aplifisa/contcs/CONTBD
jdbc.username=SYSDBA
jdbc.password=masterkey
jdbc.validationQuery=Select 1 from rdb$database
EmpresasController.java
package com.atorresbr.springapp;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.atorresbr.springapp.EmpresasService;
import com.atorresbr.springapp.Empresas;
#Controller
#RequestMapping("/")
public class EmpresasController {
// #Autowired private EmpresasDAO empresasDAO;
#Autowired private EmpresasService empresasService;
protected final Log logger = LogFactory.getLog(getClass());
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Empresas> empresas = empresasService.findAll();
model.addAttribute("empresas", empresas);
return "views/index";}
EmpresasServiceIMPL
package com.atorresbr.springapp;
//imports..
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.atorresbr.springapp.Empresas;
#Service
public class EmpresasServiceImpl implements EmpresasService {
#Autowired
private EmpresasDAO empresasDAO;
/**
* #Transactional annotation below will trigger Spring Hibernate transaction manager to automatically create
* a hibernate session. See src/main/webapp/WEB-INF/servlet-context.xml
*/
#Transactional
public List<Empresas> findAll() {
return empresasDAO.findAll();
}
}
EmpresasDAOIMPL
package com.atorresbr.springapp;
//imports..
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#SuppressWarnings({"unchecked", "rawtypes"})
public class EmpresasDAOImpl implements EmpresasDAO {
#Autowired private SessionFactory sessionFactory;
/**
* #Transactional annotation below will trigger Spring Hibernate transaction manager to automatically create
* a hibernate session. See src/main/webapp/WEB-INF/servlet-context.xml
*/
#Transactional
public List<Empresas> findAll() {
Session session = sessionFactory.getCurrentSession();
List empresas = session.createQuery("from Empresas").list();
return empresas;
}
}
Empresas.java
package com.atorresbr.springapp;
// imports ..
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Blob;
import java.util.Date;
#Entity
#Table(name = "empresas")
public class Empresas {
#Id
#Column(name = "CLAVE")
#GeneratedValue private long CLAVE;
#Column(name = "NOMBRE")
private String NOMBRE;
#Column(name = "DNICIF")
private String DNICIF;
#Column(name = "SIGLA")
private String SIGLA;
#Column(name = "VIAPUBLICA")
private String VIAPUBLICA;
#Column(name = "NUMERO")
private String NUMERO;
#Column(name = "PISO")
private String PISO;
#Column(name = "PUERTA")
private String PUERTA;
#Column(name = "MUNICIPIO")
private String MUNICIPIO;
#Column(name = "CODPOSTAL")
private String CODPOSTAL;
#Column(name = "PROVINCIA")
private String PROVINCIA;
#Column(name = "TELEFONO")
private String TELEFONO;
#Column(name = "FAX")
private String FAX;
#Column(name = "ADMON")
private String ADMON;
#Column(name = "NIVEL")
private long NIVEL;
#Column(name = "EJERCICIO")
private String EJERCICIO;
#Column(name = "FECHAINI")
private Date FECHAINI;
#Column(name = "FECHAFIN")
private Date FECHAFIN;
#Column(name = "PAG_ASIEN")
private String PAG_ASIEN;
private String COBROS;
#Column(name = "OCUPADO")
private String OCUPADO;
#Column(name = "CONTRASE")
private String CONTRASE;
#Column(name = "ACT_CONTRASE")
private String ACT_CONTRASE;
#Column(name = "BALANCE")
private String BALANCE;
#Column(name = "COOPERA")
private String COOPERA;
#Column(name = "WEB")
private String WEB;
#Column(name = "CORREO")
private String CORREO;
#Column(name = "IGIC_IVA")
private String IGIC_IVA;
#Column(name = "OBSERVACIONES")
private String OBSERVACIONES;
#Column(name = "CONTACTO")
private String CONTACTO;
#Column(name = "TELEFONO_CONT")
private String TELEFONO_CONT;
#Column(name = "CODPAIS")
private String CODPAIS;
#Column(name = "TIPO_EMP")
private String TIPO_EMP;
#Column(name = "BALANCE_UE")
private String BALANCE_UE;
#Column(name = "E_RETEN")
private String E_RETEN;
#Column(name = "FECHA_BAJA")
private Date FECHA_BAJA;
#Column(name = "GES_PROYECTOS")
private String GES_PROYECTOS;
#Column(name = "TOMO_R")
private String TOMO_R;
#Column(name = "LIBRO_R")
private String LIBRO_R;
#Column(name = "SECCION_R")
private String SECCION_R;
#Column(name = "FOLIO_R")
private String FOLIO_R;
#Column(name = "TIPO_R")
private String TIPO_R;
#Column(name = "HOJA_R")
private String HOJA_R;
#Column(name = "OTROS_R")
private String OTROS_R;
#Column(name = "REGMER")
private String REGMER;
#Column(name = "SUB_TYPE")
private Blob SUB_TYPE;
#Column(name = "ILOGO")
private String ILOGO;
#Column(name = "INUMERO")
private String INUMERO;
#Column(name = "WEBCONTACTO")
private String WEBCONTACTO;
#Column(name = "MOVILCONTACTO")
private String MOVILCONTACTO;
#Column(name = "REGVENTAS")
private String REGVENTAS;
#Column(name = "REGCOMPRAS")
private String REGCOMPRAS;
#Column(name = "SUBC_DESP1")
private String SUBC_DESP1;
#Column(name = "SUBC_DESP2")
private String SUBC_DESP2;
#Column(name = "SUBC_DESP3")
private String SUBC_DESP3;
#Column(name = "SUBC_DESP4")
private String SUBC_DESP4;
#Column(name = "SUBC_DESPI1")
private String SUBC_DESPI1;
#Column(name = "SUBC_DESPI2")
private String SUBC_DESPI2;
#Column(name = "SUBC_DESPI3")
private String SUBC_DESPI3;
#Column(name = "SUBC_DESPI4")
private String SUBC_DESPI4;
#Column(name = "SUBC_DESPI5")
private String SUBC_DESPI5;
#Column(name = "SUBC_DESPI6")
private String SUBC_DESPI6;
#Column(name = "SUBC_DESPC1")
private String SUBC_DESPC1;
#Column(name = "SUBC_DESP7")
private String SUBC_DESP7;
#Column(name = "GES_DOCU")
private String GES_DOCU;
#Column(name = "CRITERIOCAJA")
private String CRITERIOCAJA;
#Column(name = "DOC3W_REFURL")
private String DOC3W_REFURL;
#Column(name = "DOC3W_AUTOGESTION")
private String DOC3W_AUTOGESTION;
/* getters & setters */
public long getCLAVE() {
return CLAVE;
}
public void setCLAVE(long CLAVE) {
this.CLAVE = CLAVE;
}
public String getNOMBRE() {
return NOMBRE;
}
public void setNOMBRE(String NOMBRE) {
this.NOMBRE = NOMBRE;
}
.
.
.
Etc etc //setters.
Given the error:
Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 2122
SUB_TYPE
and character 2122 in the generated query is at SUB_TYPE in the generated query (around ..., empresas0_.SUB_TYPE as SUB60_0_, ...); and given that SUB_TYPE is a keyword (but not a reserved word) used to indicate the type of a blob (eg in create table or casts), my initial guess would be with:
#Column(name = "SUB_TYPE")
private Blob SUB_TYPE;
However a quick test - against a snapshot of Firebird 3 - shows that this is a valid column name. I currently don't have access to a released Firebird version (eg Firebird 2.5.3), so it is possible that some of the parser rules have been relaxed between Firebird 2.5 (or the version you are using) and Firebird 3. If that is the case, then forcing Hibernate to quote the object name might help (note the extra quotes):
#Column(name = "`SUB_TYPE`")
private Blob SUB_TYPE;

Exception in thread "main" org.hibernate.AnnotationException: #OneToOne or #ManyToOne

I want to do one-to-many mapping in hibernate,but it is showing exception,I tried a lot but unable to find solution
I have below two tables
dept
deptno -- number primary key
dname -- varchar2(10)
loc -- varchar2(10)
employee1
empno -- number primary key
username -- varchar2(10)
deptno -- number(10) foreign key
when I am not adding #Entity annotation on Dept.java class I am getting below stacktrace
21:35:11.554 [main] DEBUG o.h.i.f.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-table] -> [class org.hibernate.id.enhanced.TableGenerator]
21:35:11.554 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
21:35:11.554 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - trying to resolve system-id [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd]
21:35:11.632 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - attempting to resolve on classpath under org/hibernate/
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - located [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd] in classpath
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.url=jdbc:oracle:thin:#localhost:1521:XE
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.username=test
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.password=test
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - session-factory config [null] named class [com.beans.Employee] for mapping
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - session-factory config [null] named class [com.beans.Dept] for mapping
21:35:11.663 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - properties: {hibernate.connection.password=test, java.runtime.name=Java(TM) SE Runtime Environment, sun.boot.library.path=C:\Program Files\Java\jdk1.7.0_17\jre\bin, java.vm.version=23.7-b01, hibernate.connection.username=test, java.vm.vendor=Oracle Corporation, java.vendor.url=http://java.oracle.com/, path.separator=;, java.vm.name=Java HotSpot(TM) 64-Bit Server VM, file.encoding.pkg=sun.io, user.script=, user.country=US, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=, java.vm.specification.name=Java Virtual Machine Specification, user.dir=E:\javahyd\eclipse_new_hibernate\One_Many1, java.runtime.version=1.7.0_17-b02, java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, java.endorsed.dirs=C:\Program Files\Java\jdk1.7.0_17\jre\lib\endorsed, os.arch=amd64, java.io.tmpdir=C:\Users\rajeev\AppData\Local\Temp\, line.separator=
, java.vm.specification.vendor=Oracle Corporation, user.variant=, os.name=Windows 7, sun.jnu.encoding=Cp1252, java.library.path=C:\Program Files\Java\jdk1.7.0_17\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/bin/server;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/bin;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/lib/amd64;C:\Windows\SYSTEM32\WBEM;C:\Program Files\Java\jdk1.7.0_17\bin;C:\ORACLEXE\APP\ORACLE\PRODUCT\10.2.0\SERVER\BIN;.;.;C:\PROGRAM FILES\MYSQL\MYSQL SERVER 5.5\BIN;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files\Dell\DW WLAN Card;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\apache-maven-3.2.1\bin;C:\Windows\System32;.;E:\sts\sts-bundle\sts-3.6.0.M1;;., java.specification.name=Java Platform API Specification, java.class.version=51.0, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, os.version=6.1, user.home=C:\Users\rajeev, user.timezone=Asia/Calcutta, java.awt.printerjob=sun.awt.windows.WPrinterJob, file.encoding=Cp1252, java.specification.version=1.7, hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver, java.class.path=E:\javahyd\eclipse_new_hibernate\One_Many1\target\classes;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\annotations-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-ant.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-ha.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-tribes.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\ecj-3.7.2.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\el-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jasper-el.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jasper.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jsp-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-coyote.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-dbcp.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-es.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-fr.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-ja.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-jdbc.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-util.jar;C:\Users\rajeev\.m2\repository\ch\qos\logback\logback-core\1.1.2\logback-core-1.1.2.jar;C:\Users\rajeev\.m2\repository\ch\qos\logback\logback-classic\1.1.2\logback-classic-1.1.2.jar;C:\Users\rajeev\.m2\repository\org\slf4j\slf4j-api\1.7.6\slf4j-api-1.7.6.jar;C:\Users\rajeev\.m2\repository\com\myoracle\ojdbc14\10.2.0.1.0\ojdbc14-10.2.0.1.0.jar;C:\Users\rajeev\.m2\repository\org\hibernate\hibernate-core\3.6.10.Final\hibernate-core-3.6.10.Final.jar;C:\Users\rajeev\.m2\repository\antlr\antlr\2.7.6\antlr-2.7.6.jar;C:\Users\rajeev\.m2\repository\commons-collections\commons-collections\3.1\commons-collections-3.1.jar;C:\Users\rajeev\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Users\rajeev\.m2\repository\org\hibernate\hibernate-commons-annotations\3.2.0.Final\hibernate-commons-annotations-3.2.0.Final.jar;C:\Users\rajeev\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.0-api\1.0.1.Final\hibernate-jpa-2.0-api-1.0.1.Final.jar;C:\Users\rajeev\.m2\repository\javax\transaction\jta\1.1\jta-1.1.jar;C:\Users\rajeev\.m2\repository\javassist\javassist\3.12.1.GA\javassist-3.12.1.GA.jar, user.name=rajeev, hibernate.bytecode.use_reflection_optimizer=false, java.vm.specification.version=1.7, sun.java.command=com.test.Test, java.home=C:\Program Files\Java\jdk1.7.0_17\jre, sun.arch.data.model=64, hibernate.dialect=org.hibernate.dialect.Oracle10gDialect, hibernate.connection.url=jdbc:oracle:thin:#localhost:1521:XE, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.awt.windows.WToolkit, java.vm.info=mixed mode, java.version=1.7.0_17, java.ext.dirs=C:\Program Files\Java\jdk1.7.0_17\jre\lib\ext;C:\Windows\Sun\Java\lib\ext, sun.boot.class.path=C:\Program Files\Java\jdk1.7.0_17\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_17\jre\classes, java.vendor=Oracle Corporation, file.separator=\, java.vendor.url.bug=http://bugreport.sun.com/bugreport/, sun.io.unicode.encoding=UnicodeLittle, sun.cpu.endian=little, sun.desktop=windows, sun.cpu.isalist=amd64}
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - Preparing to build session factory with filters : {}
21:35:11.741 [main] DEBUG org.hibernate.cfg.Configuration - Processing hbm.xml files
21:35:11.741 [main] DEBUG org.hibernate.cfg.Configuration - Process annotated classes
21:35:11.756 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.beans.Employee
21:35:11.789 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3DiscriminatorColumn{logicalColumnName'DTYPE', discriminatorTypeName='string'}
21:35:11.804 [main] DEBUG org.hibernate.cfg.AnnotationBinder - no value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED
21:35:11.820 [main] DEBUG o.h.cfg.annotations.EntityBinder - Import with entity name Employee
21:35:11.820 [main] INFO o.h.cfg.annotations.EntityBinder - Bind entity com.beans.Employee on table employee1
21:35:11.867 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=empno, insertable=true, updatable=true, unique=false}
21:35:11.882 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property empno with lazy=false
21:35:11.882 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for empno
21:35:11.882 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property empno
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3JoinColumn{logicalColumnName='deptno', referencedColumn='', mappedBy=''}
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=dept, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property dept
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=deptno, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property deptno with lazy=false
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for deptno
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property deptno
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=userName, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property userName with lazy=false
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for userName
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property userName
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for empno
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for deptno
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for userName
21:35:11.898 [main] DEBUG org.hibernate.cfg.Configuration - processing fk mappings (*ToOne and JoinedSubclass)
Exception in thread "main" org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.beans.Employee.dept references an unknown entity: com.beans.Dept
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:107)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
at com.test.Test.main(Test.java:17)
when I am adding #Entity annotation on Dept.java class I am getting below stacktrace
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: com.beans.Employee column: deptno (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:676)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:698)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:720)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:474)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at com.test.Test.main(Test.java:17)
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping class="com.beans.Employee"></mapping>
<mapping class="com.beans.Dept"></mapping>
</session-factory>
</hibernate-configuration>
Dept.java
package com.beans;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Dept {
#Id
private int deptno;
private String dname;
private String loc;
#OneToMany(mappedBy = "dept")
Set<Employee> set;
public Set<Employee> getSet() {
return set;
}
public void setSet(Set<Employee> set) {
this.set = set;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
Employee.java
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "employee1")
public class Employee {
#Id
private int empno;
private String userName;
private int deptno;
#ManyToOne
#JoinColumn(name = "deptno")
private Dept dept;
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
}
Test.java
package com.test;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.beans.Dept;
import com.beans.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee();
Dept dept = new Dept();
Set<Employee> set = new HashSet<Employee>();
set.add(employee);
dept.setDeptno(11);
dept.setDname("mca");
dept.setLoc("sbp");
dept.setSet(set);
session.save(dept);
employee.setEmpno(1);
employee.setUserName("rajeev");
employee.setDept(dept);
session.save(employee);
transaction.commit();
session.close();
}
}
can anyone help me to find the mistake...
below is the githib link
git#github.com:mcarajeev/hibernate3.git
In your Employee.java you have added deptno as a join column and you have already added deptno as column so it is creating two deptno in same table which is giving Exception.
Solution : You can remove private int deptno from Employee.java as your Join column will work as foreign key.
Looking at the entities, this exception should not be thrown, however when I checked code on git, #Entity annotation is missing on Dept class, are you sure that you are using #Entity?
Note that this exception is thrown when you map an entity about which hibernate is not aware off. Like in your case, Employee has association with Dept but Dept is not known to hibernate as an entity as you have not used #Entity.
private int deptno;
#ManyToOne
#JoinColumn(name = "deptno")
private Dept dept;
Remove private int deptno, hibernate will generate it as a part of association.

Categories

Resources