I have a OneToMany data model with two entities. One machine contains many characteristics.
Problem: I am trying to create entities without a cyclic dependency.
But I get the issue:
Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 21 more
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: machine, for columns: [org.hibernate.mapping.Column(characteristics)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
... 29 more
My database:
machine:
create statement:
CREATE TABLE `machine` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8
entity:
#Entity
#Table(name = "machine")
public class Machine {
private int machine_id;
private String name;
private String description;
private Set<Characteristic> characteristics;
public Set<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(Set<Characteristic> characteristics){
this.characteristics = characteristics;
}
public Machine(){}
public Machine(String name, String description){
this.name = name;
this.description = description;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getId() {
return machine_id;
}
public void setId(int machine_id) {
this.machine_id = machine_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Characteristic
create statement:
CREATE TABLE `characteristic` (
`characteristic_id` int(11) NOT NULL AUTO_INCREMENT,
`machine_id` int(11) NOT NULL DEFAULT '0',
`name` varchar(45) DEFAULT NULL,
`description` varchar(45) DEFAULT NULL,
`type` int(11) NOT NULL,
`value` int(11) DEFAULT NULL,
PRIMARY KEY (`characteristic_id`),
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
entity:
#Entity
#Table(name = "characteristic")
public class Characteristic {
private int characteristic_id;
private String name;
private String description;
private int type;
private int value;
public Characteristic() {}
public Characteristic(String description, int type, int value) {
this.description = description;
this.type = type;
this.value = value;
}
public Characteristic(int characteristic_id, String description, int type, int value) {
this.characteristic_id = characteristic_id;
this.description = description;
this.type = type;
this.value = value;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="characteristic_id")
public int getCharacteristic_Id() {
return characteristic_id;
}
public void setCharacteristic_Id(int characteristic_id) {
this.characteristic_id = characteristic_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="type")
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Column(name="value")
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Spring-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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mego.smscloud" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/maschinedb?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="packagesToScan" value="com.mego.smscloud.entity"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
<jpa:repositories base-package="com.mego.smscloud.repository" />
</beans>
it's simply a problem with the mapping between Characteristic and Machine.
The log tells that Hibernate doesn't know which type to use for mapping.
You should add a #OneToMany annotation on method getCharacteristics() in class Machine.
You could have a look here for collection mapping at the section OneToMany Unidirectional (with or without jointable):
https://docs.jboss.org/hibernate/annotations/3.4/reference/en/html_single/#entity-mapping-association-collections
#Entity
#Table(name = "machine")
public class Machine {
private int machine_id;
private String name;
private String description;
private Set<Characteristic> characteristics;
#OneToMany
#JoinColumn(name="machine_id")
public Set<Characteristic> getCharacteristics() {
return characteristics;
}
public void setCharacteristics(Set<Characteristic> characteristics){
this.characteristics = characteristics;
}
public Machine(){}
public Machine(String name, String description){
this.name = name;
this.description = description;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
public int getId() {
return machine_id;
}
public void setId(int machine_id) {
this.machine_id = machine_id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Hope this help
Related
Hello i am having problems with assigning OneToOne relationships in my project.
This is my Player.java
#Table(name = "player")
public class Player implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "player_id", unique = true, nullable = false)
private Integer id;
#NotNull
private String username, password, email;
#NotNull
private Integer rank;
private Integer userType; // 0 - regular user, 1 - admin
private Review review;
public Player() {}
public Player(#NotNull String username, #NotNull String password, #NotNull String email, #NotNull Integer rank, Integer userType) {
this.username = username;
this.password = password;
this.email = email;
this.rank = rank;
this.userType = userType;
}
// Getters and Setters
#JsonGetter("id")
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
#JsonGetter("username")
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
#JsonGetter("password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
#JsonGetter("email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#JsonGetter("rank")
public Integer getRank() { return rank; }
public void setRank(Integer rank) { this.rank = rank; }
#JsonGetter("user_type")
public Integer getUserType() { return userType; }
public void setUserType(Integer userType) { this.userType = userType; }
public Review getReview() {
return review;
}
public void setReview(Review review) {
this.review = review;
}
}
Review.java
#Entity
#Table(name = "review")
public class Review {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "review_id", insertable = false, updatable = false, unique = true, nullable = false)
private int id;
#Column(name = "timestamp")
private Timestamp timestamp;
#Column(name = "description")
private String description;
private Player player;
// Constructors
public Review() {
}
public Review(int Id, Timestamp timestamp, String description) {
this.id = Id;
this.timestamp = timestamp;
this.description = description;
}
// Getters and Setters
#JsonGetter("id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonGetter("timestamp")
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
#JsonGetter("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonGetter("player")
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
}
player.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.montini.teamsports.model">
<class name="Player" table="player">
<meta attribute="class-description">
This class contains the player detail.
</meta>
<id name="id" type="int" column="player_id">
<generator class="native"/>
</id>
<property name="username" column="username" type="string"/>
<property name="password" column="password" type="string"/>
<property name="email" column="email" type="string"/>
<property name="rank" column="user_rank" type="int"/>
<property name="userType" column="user_type" type="int"/>
<one-to-one name="review" class="com.montini.teamsports.model.Review"
constrained="true"></one-to-one>
<!--<property name="userType">-->
<!-- <type name="org.hibernate.type.EnumType">-->
<!-- <param name="enumClass">com.montini.teamsports.model.UserType</param>-->
<!-- <param name="useNamed">true</param>-->
<!-- </type>-->
<!--</property>-->
</class>
</hibernate-mapping>
review.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.montini.teamsports.model">
<class name="Review" table="review">
<id name="id" column="review_id">
</id>
<one-to-one name="player" foreign-key="player_id" class="com.montini.teamsports.model.Player" cascade="save-update">
</one-to-one>
<property name="timestamp" column="timestamp" type="timestamp"/>
<property name="description" column="description" type="string"/>
</class>
</hibernate-mapping>
This is DDL
CREATE TABLE player
(
player_id int primary key not null auto_increment,
username varchar(30),
password varchar(30),
email varchar(50),
user_rank int,
user_type int,
unique (player_id)
);
CREATE TABLE review
(
review_id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
player_id int not null,
timestamp datetime,
description text,
unique (review_id),
KEY FK_player_review (player_id),
CONSTRAINT FK_player_review FOREIGN KEY (player_id) REFERENCES player (player_id)
);
the test class is:
public class ReviewTest {
public static final Logger log = LoggerFactory.getLogger(Review.class);
#Test
public void test1() {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
Player player = new Player();
player.setUsername("Ignas");
player.setPassword("kokokok");
player.setEmail("jojo#jojo.com");
player.setUserType(0);
player.setRank(10);
Review review = new Review();
review.setTimestamp(new Timestamp(System.currentTimeMillis()));
review.setDescription("New message from team-sport user.");
review.setPlayer(player);
player.setReview(review);
session.save(player);
session.save(review);
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
The error i am getting is this:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1348)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:435)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3221)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2389)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at com.montini.teamsports.ReviewTest.test1(ReviewTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3208)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3722)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:91)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:349)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1344)
... 63 more
Caused by: java.sql.SQLException: Field 'player_id' doesn't have a default value
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:116)
at com.mysql.cj.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1867)
at com.mysql.cj.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2029)
at com.mysql.cj.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:1970)
at com.mysql.cj.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:4996)
at com.mysql.cj.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1955)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 74 more
I think the main problem is that is tells that player_id has no default value. but when debugging this test it shows that player is assigned to review.
Seems like, you are not passing player to review while persisting.
you will have to persist player first and than before persisting the review you have fetch player for which you would like to add review and set it manually in your business logic.
I have created a PostgreSQL script just to insert a row in the customer table. The insert happens when my project is starting to run.
But it doesn't work because I'm getting the following error:
[EL Warning]: 2016-10-23 22:14:40.182--ServerSession(609762439)--?>Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at end of input
Position: 82 Error Code: 0 Call: INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, >Fax, Number) VALUES Query: DataModifyQuery(sql="INSERT INTO customer (id, Name, Adres, >PostalCode, City, Tel, Fax, Number) VALUES") [EL Warning]: 2016-10-23 22:14:40.183--ServerSession(609762439)-->Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): >org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at or near "1"
Position: 2 Error Code: 0 Call: (1, 'Kantoor Snel Transport / Distributiecentrum', >'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92'); Query: DataModifyQuery(sql="(1, 'Kantoor Snel Transport / >Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, >'92');") [EL Info]: connection: 2016-10-23 22:15:02.917-->ServerSession(609762439)-->file:/C:/Users/yomac_000/workspace/.metadata/.plugins/org.eclipse.wst.ser>ver.core/tmp0/wtpwebapps/snel-transport/WEB-INF/classes/_snel-transport >logout successful
Here is the persistence.xml file:
<?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="snel-transport" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>nl.cimsolutions.snel_transport.models.Orders</class>
<class>nl.cimsolutions.snel_transport.models.OrderLine</class>
<class>nl.cimsolutions.snel_transport.models.OrderList</class>
<class>nl.cimsolutions.snel_transport.models.Customer</class>
<class>nl.cimsolutions.snel_transport.models.Product</class>
<class>nl.cimsolutions.snel_transport.models.Category</class>
<class>nl.cimsolutions.snel_transport.models.Status</class>
<class>nl.cimsolutions.snel_transport.models.Truck</class>
<!-- <jta-data-source>java:app/snel-transport</jta-data-source> -->
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<properties>
<property
name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
<property name="eclipselink.canonicalmodel.subpackage"
value="dev" />
<property name="javax.persistence.sql-load-script-source"
value="META-INF/sql/Customer2.sql" />
<property name="javax.persistence.schema-generation-target"
value="database" />
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/snel-transport" />
<property name="javax.persistence.jdbc.user" value="transport_user" />
<property name="javax.persistence.jdbc.password"
value="admin" />
<property name="javax.persistence.jdbc.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
And here is my PostgreSQL script:
INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, Fax, Number) VALUES
(1, 'Kantoor Snel Transport / Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92');
And here is how the Customer model looks like:
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(
name = "CustomerGenerator",
allocationSize = 1,
initialValue = 1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE,
generator="CustomerGenerator")
private Long id;
private String name;
private String adres;
#Column(name="Number")
private String streetNumber;
#Column(name="PostalCode")
private String postalCode;
#Column(name="City")
private String city;
#Column(name="Tel")
private String tel;
#Column(name="Fax")
private String fax;
#OneToMany(mappedBy = "customer", targetEntity = Orders.class)
private List<Orders> orders;
public Customer() {
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "model.OrderLine[ id=" + id + " ]";
}
public String getName() {
return name;
}
public String getAdres() {
return adres;
}
public void setName(String name) {
this.name = name;
}
public void setAdres(String adres) {
this.adres = adres;
}
}
I have already tried using the PostgreSQL script in pgAdmin. And there the script works, but somehow it doesn't work in JPA.. Anyone got a clue how I can solve this problem?
I am writing a spring batch process to read the data from the cassandra table and modify it and write the data back to the cassandra table. I am using the same class to read and write the data back to the table. My job is written in an xml file and I am running that xml file itself.I am getting the following error:
The error is shown when I am trying to write the ArrayList back to the table
org.springframework.data.cassandra.mapping.VerifierMappingExceptions:
java.util.ArrayList: Cassandra entities must have the #Table,
#Persistent or #PrimaryKeyClass Annotation
It also shows
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntityMetadataVerifier.verify(BasicCassandraPersistentEntityMetadataVerifier.java:45)
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.verify(BasicCassandraPersistentEntity.java:198)
xml:
<job id="LoadStatusIndicator" job-repository="jobRepository" restartable="false">
<step id="LoadStatus" next="">
<tasklet>
<chunk reader="StatusReader" processor="ItemProcessor" writer="ItemWriter"
commit-interval="1" />
</tasklet>
</step>
</job>
<beans:bean id="ItemWriter" scope="step"
class="com.batch.writer.ItemWriter">
</beans:bean>
<beans:bean id="ItemProcessor" scope="step"
class="com.batch.processor.ItemProcessor">
</beans:bean>
<beans:bean id="Reader" scope="step"
class="com.reader.ItemReader">
<beans:property name="dataSource" ref="CassandraSource" />
</beans:bean>
applicationcontext.xml:
<beans:bean id="CassandraSource" parent="DataSourceParent">
<beans:property name="url" value="jdbc:cassandra://${cassandra.hostName}:${cassandra.port}/${cassandra.keyspace}" />
<beans:property name="driverClassName" value="org.apache.cassandra.cql.jdbc.CassandraDriver" />
</beans:bean>
reader class:
#Override
public List<Item> read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException
{
List<Item> results = new ArrayList<Item>();
try {
results = cassandraTemplate.select(query,Item.class);
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
writer classs:
#Override
public void write(List<? extends Item> item) throws Exception {
try {
cassandraTemplate.update(item);
}catch(Exception e){e.printStackTrace();}
Item class:
#Entity
//#Persistent
//#Transactional
#Table(value ="test")
//#IdClass(ItemPK.class)
//Serializable{
public class Item implements Serializable{
#Id
#PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private Integer id;
#PrimaryKeyColumn(name = "name", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String name;
#Column(value = "address")
private Float address;
public Item(){}
public Item(Integer id, String name, Float address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getAddress() {
return address;
}
public void setAddress(Float address) {
this.address = address;
}
I'm working on a Spring MVC App with JPA (Hibernate as Provider) and a PostgreSQL database. I wanted to insert results (of a time consuming task) into the database in background and created a serviceclass which implements Runnable. In the run method, I receive an entity from the repository but when I try to access a lazy collection of the entity, the database session is already closed (I get a lazy initialization exception).
The source code of my Background-Service:
#Service
#Scope("prototype")
public class ProjectServiceTestThread implements Runnable{
static Logger log = Logger.getLogger(ProjectServiceTestThread.class);
#Autowired
ProjectRepository projectRepository;
#Autowired
ScenarioRepository scenarioRepository;
#Override
#Transactional
public void run() {
List<Project> projectList = projectRepository.findByName("thread test project");
Project project;
project = projectList.get(0);
//A project can have multiple scenarios
Scenario scenario;
if (project.getScenarios().isEmpty()) { //this line fails -> lazyInitializationException - no Session
System.err.println("Creating new scenario");
scenario = new Scenario();
scenario.setName("thread test scenario");
scenario.setDescription(this + ".runServiceFunction at " + System.currentTimeMillis());
scenario.setProject(project);
scenario = scenarioRepository.save(scenario);
} else {
System.err.println("Using existing scenario");
scenario = project.getScenarios().iterator().next();
}
}
}
The Service and Spring TaskExecutor are Autowired in the Controller which is running on a Tomcat v8.0 Server.
Controller code:
#Autowired
ProjectServiceTestThreadImpl testRunnable;
#Autowired
TaskExecutor taskExecutor;
#RequestMapping(value="openproject", method=RequestMethod.GET)
public String getStringProjects(Map<String, Object> model) throws InterruptedException
{
System.err.println(this + " before call to runnable ");
testRunnable.run();
taskExecutor.execute(testRunnable);
return "openproject";
}
The log shows that the database session closes right after the findByName Query:
09:50:31,438 TRACE JdbcCoordinatorImpl:525 - Closing prepared statement [select distinct project0_.prjid as prjid1_24_, project0_.createdby as createdb2_24_, project0_.createdon as createdo3_24_, project0_.description as descript4_24_, project0_.designtarget as designta5_24_, project0_.location as location6_24_, project0_.name as name7_24_, project0_.modelid as modelid11_24_, project0_.timehorizon as timehori8_24_, project0_.updatedby as updatedb9_24_, project0_.updatedon as updated10_24_ from public.project project0_ where lower(project0_.name) like ('%'||lower('thread test project')||'%')]
09:50:31,438 TRACE JdbcCoordinatorImpl:278 - Starting after statement execution processing [ON_CLOSE]
09:50:31,438 TRACE StatefulPersistenceContext:880 - Initializing non-lazy collections
09:50:31,439 TRACE SessionImpl:357 - Closing session
09:50:31,439 TRACE JdbcCoordinatorImpl:199 - Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl#3b95a16b]
09:50:31,439 TRACE LogicalConnectionImpl:178 - Closing logical connection
09:50:31,439 DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
09:50:31,439 DEBUG LogicalConnectionImpl:264 - Released JDBC connection
09:50:31,442 TRACE LogicalConnectionImpl:190 - Logical connection closed
09:50:31,445 TRACE TransactionSynchronizationManager:243 - Removed value [org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$DefaultCrudMethodMetadata#7cc8f09] for key [public abstract java.util.List eu.cite.repository.ProjectRepository.findByName(java.lang.String)] from thread [myExecutor-1]
09:50:31,451 TRACE LazyInitializationException:53 - failed to lazily initialize a collection of role: eu.cite.model.Project.scenarios, could not initialize proxy - no Session
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: eu.cite.model.Project.scenarios, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:155)
at org.hibernate.collection.internal.PersistentSet.isEmpty(PersistentSet.java:166)
at eu.cite.service.ProjectServiceTestThread.run(ProjectServiceTestThread.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Configuration:
<context:component-scan base-package="eu.cite.repository, eu.cite.service" scoped-proxy="targetClass" />
<jpa:repositories base-package="eu.cite.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit"/>
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<entry key="hibernate.format_sql" value="true"/>
<entry key="hibernate.jdbc.batch_size" value="50"/>
<entry key="hibernate.order_inserts" value="true"/>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<bean id="ModelMapper" class="org.modelmapper.ModelMapper"></bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5432/Cite?autoReconnect=true"></property>
<property name="username" value="cite"></property>
<property name="password" value="***"></property>
</bean>
<task:executor id="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>
Can somebody tell me why it does not work this way? I figured out some ways to make it work, but I don't understand why it does not work with the code above. These three approaches correctly insert the Scenario, without closing the database Session in between:
remove #Service from ProjectServiceTestThread and register the bean in the config manually
Not implement Runnable and annotate the run() method of ProjectServiceTestThread with #Async
Not using the Spring Task Executor
Edit - Project entity:
#Entity
#Table(name = "project", schema = "public", uniqueConstraints = #UniqueConstraint(columnNames = "name"))
public class Project implements java.io.Serializable {
private int prjid;
private SimulationModel simulationmodel;
private String name;
private String description;
private String designtarget;
private Date timehorizon;
private String location;
private Date createdon;
private Date updatedon;
private Integer createdby;
private Integer updatedby;
private Set<ObjectiveFunction> objectivefunctions = new HashSet<ObjectiveFunction>(
0);
private Set<Scenario> scenarios = new HashSet<Scenario>(0);
private Set<ScenarioGenerator> scenariogenerators = new HashSet<ScenarioGenerator>(
0);
private List<Component> components = new ArrayList<Component>();
private Set<OptConstraint> optconstraints = new HashSet<OptConstraint>(0);
private Set<SearchConstraint> searchconstraints = new HashSet<SearchConstraint>(
0);
private Set<Metric> metrics = new HashSet<Metric>(0);
private Set<UserGroupProject> usergroupprojects = new HashSet<UserGroupProject>(
0);
private Set<ExtParam> extparams = new HashSet<ExtParam>(0);
public Project() {
}
public Project(int prjid, String name) {
this.prjid = prjid;
this.name = name;
}
public Project(int prjid, SimulationModel simulationmodel, String name,
String description, String designtarget, Date timehorizon, String location,
Date createdon, Date updatedon, Integer createdby,
Integer updatedby, Set<ObjectiveFunction> objectivefunctions,
Set<Scenario> scenarios, Set<ScenarioGenerator> scenariogenerators,
List<Component> components, Set<OptConstraint> optconstraints,
Set<SearchConstraint> searchconstraints, Set<Metric> metrics,
Set<UserGroupProject> usergroupprojects, Set<ExtParam> extparams) {
this.prjid = prjid;
this.simulationmodel = simulationmodel;
this.name = name;
this.description = description;
this.designtarget = designtarget;
this.timehorizon = timehorizon;
this.location = location;
this.createdon = createdon;
this.updatedon = updatedon;
this.createdby = createdby;
this.updatedby = updatedby;
this.objectivefunctions = objectivefunctions;
this.scenarios = scenarios;
this.scenariogenerators = scenariogenerators;
this.components = components;
this.optconstraints = optconstraints;
this.searchconstraints = searchconstraints;
this.metrics = metrics;
this.usergroupprojects = usergroupprojects;
this.extparams = extparams;
}
#SequenceGenerator(name="project_prjid_seq",sequenceName="project_prjid_seq") #GeneratedValue(strategy = GenerationType.SEQUENCE, generator="project_prjid_seq")
#Id
#Column(name = "prjid", unique = true, nullable = false)
public int getPrjid() {
return this.prjid;
}
public void setPrjid(int prjid) {
this.prjid = prjid;
}
#ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.PERSIST)
#JoinColumn(name = "modelid")
public SimulationModel getSimulationmodel() {
return this.simulationmodel;
}
public void setSimulationmodel(SimulationModel simulationmodel) {
this.simulationmodel = simulationmodel;
}
#Column(name = "name", unique = true, nullable = false, length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "designtarget", length = 50)
public String getDesigntarget() {
return this.designtarget;
}
public void setDesigntarget(String designtarget) {
this.designtarget = designtarget;
}
#Temporal(TemporalType.TIME)
#Column(name = "timehorizon", length = 15)
public Date getTimehorizon() {
return this.timehorizon;
}
public void setTimehorizon(Date timehorizon) {
this.timehorizon = timehorizon;
}
#Column(name = "location")
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "createdon", length = 22)
public Date getCreatedon() {
return this.createdon;
}
public void setCreatedon(Date createdon) {
this.createdon = createdon;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updatedon", length = 22)
public Date getUpdatedon() {
return this.updatedon;
}
public void setUpdatedon(Date updatedon) {
this.updatedon = updatedon;
}
#Column(name = "createdby")
public Integer getCreatedby() {
return this.createdby;
}
public void setCreatedby(Integer createdby) {
this.createdby = createdby;
}
#Column(name = "updatedby")
public Integer getUpdatedby() {
return this.updatedby;
}
public void setUpdatedby(Integer updatedby) {
this.updatedby = updatedby;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ObjectiveFunction> getObjectivefunctions() {
return this.objectivefunctions;
}
public void setObjectivefunctions(Set<ObjectiveFunction> objectivefunctions) {
this.objectivefunctions = objectivefunctions;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<Scenario> getScenarios() {
return this.scenarios;
}
public void setScenarios(Set<Scenario> scenarios) {
this.scenarios = scenarios;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ScenarioGenerator> getScenariogenerators() {
return this.scenariogenerators;
}
public void setScenariogenerators(Set<ScenarioGenerator> scenariogenerators) {
this.scenariogenerators = scenariogenerators;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
#OrderBy("componentid")
public List<Component> getComponents() {
return this.components;
}
public void setComponents(List<Component> components) {
this.components = components;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<OptConstraint> getOptconstraints() {
return this.optconstraints;
}
public void setOptconstraints(Set<OptConstraint> optconstraints) {
this.optconstraints = optconstraints;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<SearchConstraint> getSearchconstraints() {
return this.searchconstraints;
}
public void setSearchconstraints(Set<SearchConstraint> searchconstraints) {
this.searchconstraints = searchconstraints;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<Metric> getMetrics() {
return this.metrics;
}
public void setMetrics(Set<Metric> metrics) {
this.metrics = metrics;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<UserGroupProject> getUsergroupprojects() {
return this.usergroupprojects;
}
public void setUsergroupprojects(Set<UserGroupProject> usergroupprojects) {
this.usergroupprojects = usergroupprojects;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project")
public Set<ExtParam> getExtparams() {
return this.extparams;
}
public void setExtparams(Set<ExtParam> extparams) {
this.extparams = extparams;
}
I found the issue in my appConfig.java: There was another component scan, which scanned all packages, including services:
#Configuration
#EnableWebMvc
#ComponentScan({"eu.cite"})
public class appConfig extends WebMvcConfigurerAdapter {
this seems to undo the transaction configuration from the xml. I changed the component scan to eu.cite.controller so my servlet is still able to find the controller and does not interfere with the other config
I was trying to get data from a MySQL database using the Spring utility ResultSetExtractor, but I got the following exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext2.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.resultset.Test.main(Test.java:11)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1012)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:857)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1341)
... 13 more
Employee.java
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public Employee()
{
}
}
EmployeeDao.java
public class EmployeeDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()){
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
}
}
and applicationContext2.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
These all are java files I am using. It says the setter's return type doesn't match with the getter's, but I checked it, and it is correct there.
The problem is in
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
Try changing the name="jdbcTemplate" to name="template". Since you have given name as jdbcTemplate spring will search for a setter method with name setJdbcTemplate() in EmployeeDao class, but the acutal method you have is setTemplate()
Controller extends MethodNameResolver
public final void setMethodNameResolver(
MethodNameResolver methodNameResolver) {
this.methodNameResolver = methodNameResolver;
}
public final MethodNameResolver getMethodNameResolver() {
return this.methodNameResolver;
}
remove spring Annotation like #controller #AutoWired