Hibernate says non-existent column is unknown...obviously - mysql

Im starting to adapt my spring boot project to use jpa / hibernate. at this stage i simply want to retrieve the id of a table in mysql database.
Here are the relevant classes:
#SpringBootApplication
#ComponentScan(basePackages = {"rest.api.controller", "dao", rest.api.model", "rest.api.config"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner demo(PostRepository repository) {
return (args) -> {
// save a couple of customers
repository.findAll();
};
}
}
#Entity
#Table(name="post")
public class Post {
private String text;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private long id;
#Column(name="sender_id")
private #JsonIgnore long senderId;
private #JsonIgnore long eventId;
private #JsonIgnore final String selectSql = " text, sender_id, event_id";
protected Post() {}
public Post(long id, float latitude, float longitude, Date created, String ip,
String text, long senderId, long eventId) {
this.text = text;
this.senderId = senderId;
this.eventId = eventId;
}
public Post(String text, long senderId, long eventId) {
this.text = text;
this.senderId = senderId;
this.eventId = eventId;
}
public String getText() {
return text;
}
public long getSenderId() {
return senderId;
}
public long getEventId() {
return eventId;
}
public void setId(long id) {
this.id = id;
}
}
public interface PostRepository extends CrudRepository<Post, Long> {
}
And mysql for the post table:
CREATE TABLE `post` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`text` varchar(4096) NOT NULL,
`sender_id` bigint(20) NOT NULL,
`event_id` bigint(20) DEFAULT NULL,
`created` datetime NOT NULL,
`ip` varchar(20) NOT NULL,
`latitude` float DEFAULT NULL,
`longitude` float DEFAULT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `post_sent_by_user` (`sender_id`),
CONSTRAINT `post_sent_by_user` FOREIGN KEY
I get the following error
2016-06-23 20:39:06.739 WARN 6895 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2016-06-23 20:39:06.740 ERROR 6895 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'post0_.select_sql' in 'field list'
2016-06-23 20:39:06.750 WARN 6895 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 1054, SQLState: 42S22
2016-06-23 20:39:06.751 WARN 6895 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'post0_.select_sql' in 'field list'
2016-06-23 20:39:06.770 ERROR 6895 --- [ main] o.s.boot.SpringApplication : Application startup failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:809) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:790) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:777) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
at rest.api.Application.main(Application.java:16) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:242) ~[spring-orm-4.2.6.RELEASE.jar:4.2.6.RELEASE]
For the life of me, i cant work out why it is looking for a column with such a bizzare name as "post0_.select_sql" - doesnt seem at all related to my table or column.
I have googled arround for a while, but could not find anything to explain this.
Id be very grateful if somebody could help me here. (Im sure it should be simple as im not really attempting anything complex yet)
Thanks

Because you told Hibernate that your entity had a persistent field named that way:
private #JsonIgnore final String selectSql
I have no idea what this field is for and why it is in your entity, but it should probably be elsewhere, or at least defined as a constant (i.e. made static) or at the very least annotated by #Transient so that Hibernate knows it's not part of the persistent properties.

Related

Cannot invoke "javax.persistence.EntityManagerFactory.createEntityManager()" because "this.entityManagerFactory" is null

I am getting NullPointerException for the following piece of code:
#SpringBootApplication
public class SpringBootJpaExampleApplication {
#PersistenceUnit
private EntityManagerFactory entityManagerFactory;
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaExampleApplication.class, args);
}
#PostConstruct
public void start(){
Employee e = new Employee();
e.setDob(new Date());
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(e);
transaction.commit();
entityManager.close();
}
}
I am trying to create Employee table in MySQL through Spring Boot but getting null pointer exception. I am out of ideas regarding the fix. Kindly help !!!
com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.main(SpringBootJpaExampleApplication.java:19) ~[classes/:na]
Caused by: java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManagerFactory.createEntityManager()" because "this.entityManagerFactory" is null
at com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.start(SpringBootJpaExampleApplication.java:28) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
... 17 common frames omitted
Process finished with exit code 1

Spring Boot- Duplicate entry for key 'PRIMARY'

I am new to Spring Boot. I am trying to use the save() functionality via the JPA library using Postman for the first time. My database is a legacy Mysql database. Generically speaking, this table contains data of baseball players who have been drafted into a fantasy baseball league. The primary key of my table is 'play_id', and I also track the player's 'mlb_id' (Major League Baseball's unique identifier) in the same table.
Here is my code:
Table setup in Mysql:
CREATE TABLE `mlb_rosters` (
`play_id` int(10) NOT NULL,
`mlb_id` int(10) NOT NULL,
`name_first` varbinary(255) NOT NULL,
`name_last` varbinary(255) NOT NULL,
`bats` varchar(1) NOT NULL,
`throws` varchar(1) NOT NULL,
`birthday` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `mlb_rosters`
ADD PRIMARY KEY (`play_id`),
ADD UNIQUE KEY `mlb_id` (`mlb_id`),
ADD UNIQUE KEY `mlb_id_2` (`mlb_id`);
ALTER TABLE `mlb_rosters`
MODIFY `play_id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6730;
I also ran insert statements for approximately ~1500 players, so this is not a blank table.
My object in Springboot:
package com.example.demo.entities;
import javax.persistence.*;
#Entity
#Table(name="mlb_rosters")
public class IbcMlbPlayer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="play_id", columnDefinition = "int(10)")
private Integer playId;
#Column(name="mlb_id")
private Integer mlbId;
#Column(name="name_first", columnDefinition = "varbinary(255)")
private String nameFirst;
#Column(name="name_last", columnDefinition = "varbinary(255)")
private String nameLast;
#Column(name="bats")
private String bats;
#Column(name="throws")
private String thrws;
#Column(name="birthday")
private String birthday;
public IbcMlbPlayer(){
}
public Integer getPlayId() {
return playId;
}
public void setPlayId(Integer playId) {
this.playId = playId;
}
public Integer getMlbId() {
return mlbId;
}
public void setMlbId(Integer mlbId) {
this.mlbId = mlbId;
}
public String getNameFirst() {
return nameFirst;
}
public void setNameFirst(String nameFirst) {
this.nameFirst = nameFirst;
}
public String getNameLast() {
return nameLast;
}
public void setNameLast(String nameLast) {
this.nameLast = nameLast;
}
public String getBats() {
return bats;
}
public void setBats(String bats) {
this.bats = bats;
}
public String getThrws() {
return thrws;
}
public void setThrws(String thrws) {
this.thrws = thrws;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
The relevant path of my controller:
#PostMapping(value = "/saveIbcMlbPlayer")
public IbcMlbPlayer saveIbcMlbPlayer(#RequestBody IbcMlbPlayer ibcMlbPlayer){
return ibcMlbPlayerDao.save(ibcMlbPlayer);
}
My Dao:
package com.example.demo.dao;
import com.example.demo.entities.IbcMlbPlayer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface IbcMlbPlayerDao extends JpaRepository<IbcMlbPlayer, Integer> {
}
When I attempt to do a Post request to the save path and pass in the JSON object of the player who I'm attempting to create, I get the following error:
Duplicate entry '25' for key 'PRIMARY'
In this case, I've tried this 25 times, so Postman/Spring Boot keep incrementing the 'play_id' field by 1 (this number goes up in the error message by one each time I test).
I understand the error, for whatever reason, Spring Boot isn't getting the max value of the 'play_id' field, incrementing it by one, and then attempting to do the insert. I would have expected 'play_id' to be 6730, which I believe is the table's max play_id plus one. Does anyone know how to fix this? Any help would be really appreciated!
AUTO shouldn't be used as GenerationType you must use IDENTITY
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="play_id", columnDefinition = "int(10)")
private Integer playId;

Spring Hibernate - Invalid value for getLong() - 'United Kingdom - UTC +0:00'

I guess hibernate is trying to assign a String value fetched from the database to long.Have done many-to-one unidirectional mapping.I'm trying to display the values from the region table in a drop down in CorporateGroupForm.jsp
CorporateGroup.java
#Entity
#Table(name="corporate_group")
public class CorporateGroup extends BaseObject implements Serializable {
private Region region;
private Long id;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id")
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
} }
corporateGroupForm.jsp
<li>
<appfuse:label styleClass="desc" key="corporateGroupDetail.region"/>
<select name="regionDesc">
<option value=""><fmt:message key="select.pleaseSelect"/></option>
<c:forEach var="region" items="${regionsList}">
<c:set var="selected" value="${corporateGroup.region ne null and corporateGroup.region.regionDesc eq region.regionDesc}"/>
<option ${selected ? 'selected' : ''} value="${region.regionDesc }">${region.regionDesc } </option>
</c:forEach>
</select>
</li>
DB:
CREATE TABLE `corporate_group` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`comment` text,`name` varchar(255) NOT NULL,`parent_id`bigint(20) DEFAULT NULL,`primary_contact_id` bigint(20) DEFAULT NULL,`account_manager_email` varchar(255) DEFAULT NULL,`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,`region_description` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `name` (`name`),KEY `FK61BCC225C8E0340A` (`parent_id`),KEY `FK61BC225F0655E4F` (`primary_contact_id`),KEY `FK_REGION_idx` (`region_description`),CONSTRAINT `fk_region` FOREIGN KEY (`region_description`) REFERENCES `region` (`region_description`) ON DELETE NO ACTION ON UPDATE NO ACTION,CONSTRAINT `FK61BC225F0655E4F` FOREIGN KEY (`primary_contact_id`) REFERENCES `app_user` (`id`),CONSTRAINT `FK61BCC225C8E0340A` FOREIGN KEY (`parent_id`) REFERENCES `corporate_group` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=843 DEFAULT CHARSET=latin1;
CREATE TABLE `region` (`id` bigint(20) NOT NULL,`country_code` varchar(50) NOT NULL,country_name` varchar(100) NOT NULL,`time_zone` varchar(100) NOT NULL,`region_description` varchar(255) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `description_UNIQUE` (`region_description`),KEY `id` (`id`),KEY `region_description` (`region_description`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Exception Stack Trace :
Hibernate: select corporateg0_.id as id2_,
corporateg0_.account_manager_email as account2_2_,
corporateg0_.comment as comment2_, corporateg0_.name as name2_,
corporateg0_.parent_id as parent6_2_, corporateg0_.primary_contact_id
as primary5_2_, corporateg0_.region_description as region7_2_ from
corporate_group corporateg0_ order by corporateg0_.name WARN
[http-bio-9080-exec-1] JDBCExceptionReporter.logExceptions(77) | SQL
Error: 0, SQLState: S1009 WARN [http-bio-9080-exec-1]
JDBCExceptionReporter.logExceptions(77) | SQL Error: 0, SQLState:
S1009 ERROR [http-bio-9080-exec-1]
JDBCExceptionReporter.logExceptions(78) | Invalid value for getLong()
- 'UK -UTC +0:00' ERROR [http-bio-9080-exec-1] JDBCExceptionReporter.logExceptions(78) | Invalid value for getLong()
- 'UK -UTC +0:00'
The error on the web page :
Data Access Failure
Hibernate operation: could not execute query; uncategorized SQLException for SQL [select corporateg0_.id as id2_, corporateg0_.account_manager_email as account2_2_, corporateg0_.comment as comment2_, corporateg0_.name as name2_, corporateg0_.parent_id as parent7_2_, corporateg0_.primary_contact_id as primary5_2_, corporateg0_.region_description as region6_2_ from corporate_group corporateg0_ order by corporateg0_.name]; SQL state [S1009]; error code [0]; Invalid value for getLong() - 'UK -UTC +0:00'; nested exception is java.sql.SQLException: Invalid value for getLong() - 'UK -UTC +0:00'
Region.java
#Entity
#Table(name = "region")
public class Region extends BaseObject implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String countryCode;
private String countryName;
private String timeZone;
private String regionDesc;
#Column(name="country_code",nullable=false)
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Column(name="country_name",nullable=false)
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
#Column(name="time_zone",nullable=false)
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
#Column(name="region_description",nullable=false)
public String getRegionDesc() {
return regionDesc;
}
public void setRegionDesc(String regionDesc) {
this.regionDesc = regionDesc;
}
#Override
public String toString() {
StringBuffer strBuff = new StringBuffer();
if (getId() != null) {
strBuff = strBuff.append("ID:" + getId() + ",");
strBuff = strBuff.append("Country Name:" + getCountryName() + ",");
strBuff = strBuff.append("Country Code:" + getCountryCode() + ",");
strBuff = strBuff.append("Timezone:" + getTimeZone() + ",");
strBuff = strBuff.append("Region Description:" + getRegionDesc() + ",");
}
return strBuff.toString();
}
#Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
if (!(o instanceof Region)) {
return false;
}
Region reg = (Region) o;
return !(regionDesc != null ? !regionDesc.equals(reg.getRegionDesc()) : reg.getRegionDesc() != null);
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
int hashcode = 0;
if (this.regionDesc != null) {
hashcode = hashcode + this.regionDesc.hashCode();
}
return hashcode;
}
}
Now a different error :
ERROR [localhost-startStop-1 ContextLoader.initWebApplicationContext(215) | Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainProxyPostProcessor': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot create inner bean '(inner bean)' of type [org.springframework.transaction.interceptor.TransactionInterceptor] while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext-dao.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dao.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.canvas8.model.CorporateGroup column: id (should be mapped with insert="false" update="false")
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:405)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:366)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1081)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1877)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
In your CorporateGroup entity class, you mapped region with region_description of Region entity which has a primary key of Long
#ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinColumn(name="region_description")
public Region getRegion() {
return region;
}
What you can do is you can map region member variable of CorporateGroup to primary key of Region entity class not the region_description.
Regarding this error :
Repeated column in mapping for entity:
com.canvas8.model.CorporateGroup column: id (should be mapped with
insert="false" update="false")
The error message is obvious, you have mapped same column twice. Refer this and fix the issue.
Hope this helps!
I was able to specify the referenced column name to resolve the issue for me. I didn't want to eager fetch the entities since it would only be used sometimes and didn't have permissions to modify the database schema.
Try this:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "region_description", referencedColumnName = "region_description")
private Region region;

jpa project with wampserver cant put anything to DB

I've created a database and added the employee table with the following code
CREATE TABLE IF NOT EXISTS `employee` (
`Idemployee` int(11) NOT NULL,
`fIrstname` varchar(45) DEFAULT NULL,
`lastname` varchar(45) DEFAULT NULL,
`emaIl` varchar(45) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
--
--
--
INSERT INTO `employee` (`Idemployee`, `fIrstname`, `lastname`, `emaIl`) VALUES
(2, 'Pranil', 'kharkar', 'someMail#gmail.com'),
(5, 'prasad', 'kharkar', 'someMail#gmail.com'),
(8, 'prasad', 'kharkar', 'someMail#gmail.com'),
(9, 'prasad', 'kharkar', 'someMail#gmail.com'),
(10, 'Pranil', 'kharkar', 'someMail#gmail.com'),
(11, 'Pranil', 'kharkar', 'someMail#gmail.com'),
(13, 'prasad', 'kharkar', 'someMail#gmail.com'),
(14, 'prasad', 'kharkar', 'someMail#gmail.com'),
(15, 'Murat', 'Kandemir', 'cmkTurkiye#gmail.com'),
(16, 'Murat2', 'Kandemir2', 'cmkTurkiye#gmail.com');
--
--
--
--
ALTER TABLE `employee`
ADD PRIMARY KEY (`Idemployee`);
--
--
--
--
--
--
ALTER TABLE `employee`
MODIFY `Idemployee` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=17;
and then created jpa project and created these 2 code pieces below for adding someone to table;
package com.thejavageek.jpa;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.thejavageek.jpa.entities.Employee;
public class Test {
public static void main(String[] args) throws IOException {
/* Create EntityManagerFactory */
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("kurumsaljava");
/* Create and populate Entity */
Employee employee = new Employee();
employee.setFirstname("Ahmet");
employee.setLastname("Mercan");
employee.setEmail("cmkTurkiye#gmail.com");
//employee.setIdEmployee();
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
/* Persist entity */
em.getTransaction().begin();
em.persist(employee);
em.getTransaction().commit();
/* CMK UPDATE
*/
/* Update routines begin*/
/*
int iEdit = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Employee Number To Edit");
//String iEdit = br.readLine();
try{
iEdit = Integer.parseInt(br.readLine());
}catch(NumberFormatException nfe){
System.err.println("Invalid Format!");
}
employee = em.find(Employee.class, iEdit);
em.getTransaction().begin();
employee.setFirstname("Murat7");
employee.setLastname("Celal");
System.out.println("Employee after updation :- " + employee);
em.getTransaction().commit();
*/
/*Update routines finish*/
// CMK DELETE
/* Delete routines begin*/
/*
int iRemove = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Employee Number To Remove");
try{
iRemove = Integer.parseInt(br.readLine());
}catch(NumberFormatException nfe){
System.err.println("Invalid Format!");
}
// Remove entity
employee = em.find(Employee.class, iRemove);
System.out.println(employee);
em.getTransaction().begin();
em.remove(employee);
em.getTransaction().commit();
*/
/*Delete routines finish*/
/* CMK
*/
/* Retrieve entity */
/*
employee = em.find(Employee.class, iEdit);
System.out.println(employee);
*/
/* Check whether entity is removed or not */
/*employee = em.find(Employee.class, 1);
System.out.println("Employee after removal :- " + employee);*/
}
}
and Employee.java;
package com.thejavageek.jpa.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Employee
*
*/
#Entity
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6984979000774926570L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int idEmployee;
private String email;
private String firstname;
private String lastname;
public Employee() {
}
public int getIdEmployee() {
return this.idEmployee;
}
public void setIdEmployee(int IdEmployee) {
this.idEmployee = IdEmployee;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "Employee [email=" + email
+ ", firstname=" + firstname + ", lastname=" + lastname + "]";
}
}
and persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="kurumsaljava">
<class>com.thejavageek.jpa.entities.Employee</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/kurumsaljava?useSSL=false" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
database name is kurumsaljava.I am getting these errors couldnt solve them
[EL Warning]: 2016-04-27 15:45:04.913--UnitOfWork(1576499395)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?L, F?RSTNAME, LASTNAME) VALUES ('cmkTurkiye#gmail.com', 'Ahmet', 'Mercan')' at line 1
Error Code: 1064
Call: INSERT INTO EMPLOYEE (EMAİL, FİRSTNAME, LASTNAME) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(Employee [email=cmkTurkiye#gmail.com, firstname=Ahmet, lastname=Mercan])
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?L, F?RSTNAME, LASTNAME) VALUES ('cmkTurkiye#gmail.com', 'Ahmet', 'Mercan')' at line 1
Error Code: 1064
Call: INSERT INTO EMPLOYEE (EMAİL, FİRSTNAME, LASTNAME) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(Employee [email=cmkTurkiye#gmail.com, firstname=Ahmet, lastname=Mercan])
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
at com.thejavageek.jpa.Test.main(Test.java:35)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?L, F?RSTNAME, LASTNAME) VALUES ('cmkTurkiye#gmail.com', 'Ahmet', 'Mercan')' at line 1
Error Code: 1064
Call: INSERT INTO EMPLOYEE (EMAİL, FİRSTNAME, LASTNAME) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(Employee [email=cmkTurkiye#gmail.com, firstname=Ahmet, lastname=Mercan])
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:900)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:962)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:631)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:798)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1737)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:226)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:125)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4207)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1441)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1531)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:277)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1169)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:132)
... 1 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?L, F?RSTNAME, LASTNAME) VALUES ('cmkTurkiye#gmail.com', 'Ahmet', 'Mercan')' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5094)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:890)
... 32 more
waiting for your answers.
As RiggsFolly said above i changed the Employee class's this parts i's to I;
#Override
public String toString() {
return "Employee [email=" + email
+ ", firstname=" + firstname + ", lastname=" + lastname + "]";
}
}
and added some addition to persistence.xml's connection string;
localhost:3306/example?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
and it is working thx

#ManagedBean issues getting relational data

I have this weird problem that throws not really useful errors. I'm trying to display data from Entity Bean in Primefaces table. I have two projects, one for front end, other one for backend. Thing is, the Entity Bean has #OneToMany and #ManyToOne relation, and they seem to cause the problems, because if I null them no errors happen, but I need that data so it's not a solution.
BACKEND:
Key parts of entity:
#Entity
#Table(name = "business_process_tasks")
public class BusinessProcessTasks implements java.io.Serializable {
....
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="process")
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
#OneToMany(mappedBy = "processTask")
public List<BusinessProcessTasksMeta> getMeta() {
return meta;
}
public void setMeta(List<BusinessProcessTasksMeta> meta) {
this.meta = meta;
}
}
Key parts of EJB:
#Override
public List<BusinessProcessTasks> getList(int processId) {
EntityManager em = emf.createEntityManager();
String q = "SELECT t from " + BusinessProcessTasks.class.getName() + " t where process="+processId;
Query query = em.createQuery(q);
List<BusinessProcessTasks> items = query.getResultList();
for(int i = 0;i<items.size();i++){
BusinessProcessTasks t = (BusinessProcessTasks) items.get(i);
//IF I SET THESE TO NULL NO ERRORS SHOW
t.setProcess(null);
t.setMeta(null);
}
em.close();
return items;
}
FRONTEND:
Key parts of #ManagedBean:
#ManagedBean(name = "processTasksTableBean")
#ViewScoped
public class ProcessTasksTableBean {
.....
#PostConstruct
void initialiseSession() {
System.out.println("Bean running");
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
//GETTING ID FROM URL
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
pageProcessId = Integer.parseInt(request.getParameter("id"));
processTasksBeanRemote = doLookup();
//ONLY PLACE IN PROJECT WHERE ERROR IS REFERENCED IN CONSOLE IS HERE
processTasksList = processTasksBeanRemote.getList(pageProcessId);
}
.....
}
Eclipse console - log is very long, if required I will post it all, now just key parts:
09:34:58,377 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8189-3) Error Rendering View[/ProcessTasks.xhtml]: java.lang.IllegalStateException: JBAS011048: Failed to construct component instance
Caused by: java.lang.RuntimeException: ClassNotFoundException marshaling EJB parameters
Caused by: java.lang.ClassNotFoundException: org.hibernate.collection.internal.PersistentBag from [Module "deployment.bpmweb.war:main" from Service Module Loader]
09:34:58,403 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/bpmweb].[Faces Servlet]] (http-localhost-127.0.0.1-8189-3) Servlet.service() for servlet Faces Servlet threw exception: java.lang.ClassNotFoundException: org.hibernate.collection.internal.PersistentBag from [Module "deployment.bpmweb.war:main" from Service Module Loader]
Issue resolved, I downloaded latest Hibernate core from http://mvnrepository.com/artifact/org.hibernate/hibernate-core/4.3.4.Final and all seems fine. Quite wierd, since I add my Jboss runtime libs to each project through build path.