#Formula Hibernate Annotation not evaluated - java

i just found out about the #Formula Annotation in Hibernate, but cannot get it to work.
I Tried using a hibernate Session to access the entites as well as a JPA Entitymanager with persistence.xml, in both cases my #Formula annotated field remains "null".
my Entity (copied from an Example):
#Entity(name = "Account")
public static class Account {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
private Long id;
private Double credit;
private Double rate;
#Formula(value = "credit * rate")
private Double interest;
//Getters and setters omitted for brevity
}
My Test-Setup (initializing a Session an an entitymanager for Test cases):
private SessionFactory sessionFactory;
private Session session = null;
EntityManager em;
#Before
public void before() {
EntityManagerFactory emf=Persistence.createEntityManagerFactory("test-pu");
em=emf.createEntityManager();
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(TestEntity.class);
configuration.addAnnotatedClass(Account.class);
configuration.setProperty("hibernate.dialect",
"org.hibernate.dialect.PostgreSQL94Dialect");
configuration.setProperty("hibernate.connection.driver_class",
"org.postgresql.Driver");
configuration.setProperty("hibernate.connection.url",
"jdbc:postgresql://localhost:5432/Archiv");
configuration.setProperty("hibernate.hbm2ddl.auto",
"create");
configuration.setProperty("hibernate.connection.username",
"postgres");
configuration.setProperty("hibernate.connection.password",
"postgres");
sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
}
The persistence.xml for the entitymanager:
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="test-pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.test.ORMTest$Account</class>
<class>com.test.ORMTest$TestEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/Archiv"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="postgres"/>
<property name="hibernate.format_sql" value="true"/>
<property name="javax.persistence.validation.mode" value="NONE"/>
<property name="hibernate.service.allow_crawling" value="false"/>
<property name="hibernate.session.events.log" value="true"/>
</properties>
</persistence-unit>
</persistence>
And last but not least, the Test Code:
#Test public void emTest(){
em.getTransaction().begin();
Account account = new Account();
account.credit=100.0;
account.rate=0.1;
em.persist(account);
em.getTransaction().commit();
em.getTransaction().begin();
Account account1 = em.find(Account.class, 1l);
Double d = account1.getInterest();
System.out.println(d);
em.getTransaction().commit();
}
#Test
public void sessionTest() {
Transaction transaction = session.beginTransaction();
Account account = new Account();
account.credit=100.0;
account.rate=0.1;
session.save(account);
transaction.commit();
transaction = session.beginTransaction();
Account account1= session.get(Account.class, 1);
Double d = account1.getInterest();
System.out.println(d);
transaction.commit();
}
Both Cases print "null" for d.
According to the examples both cases should work. Anyone firm with Hibernate to tell me where i went wrong ?:/

Make sure that the object you expect to be set with Formula, is not getting loaded from the cache(where it having the same not set)

Related

I don't know why my very simple JPA project doesn't work

I have org.postgresql.util.PSQLException: ERROR: relation "roles" does not exist, and I don't know why.
Entity class
package com.example.SpringBootTest1.model;
import lombok.*;
import javax.persistence.*;
#ToString
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "roles")
public class Role
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Setter
#Getter
private int id;
#Setter
#Getter
#Column(name = "name")
private String name;
}
main()
public static void main(String[] args)
{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("role_pu");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Role role1 = new Role();
role1.setName("role111");
entityManager.persist(role1);
entityManager.getTransaction().commit();
entityManagerFactory.close();
entityManager.close();
}
resources/META-INF/persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="role_pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.SpringBootTest1.model.Role</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="123"/>
<property name="dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hdm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
In pom.xml I have
hibernate-core
postgresql
lombok
So why I have such error and why is that? I have read this question and it doesn't help me.
In modern Hibernate versions, the property hdm2ddl.auto should be hibernate.hbm2ddl.auto or javax.persistence.schema-generation.database.action.
https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl

Tomcat + hibernate = no persistent classes found for query class

I'm developing a web app and deploying it on Tomcat 7.0. My app uses a MySQL database. I've already configured connection between app and database and wanted to add Hibernate 5.2.5 support. I can communicate with database via Hibernate console with configuration below, and it works when I use it in non-web app. The problem is only when I deploy it on server. I get warning
no persistent classes found for query class: from entities.UserH
and then 500 server error caused by it.
My entity class:
#Entity
#Table(name = "users", uniqueConstraints = {#UniqueConstraint(columnNames = {"id"})})
public class UserH {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column(name = "login", nullable = false, length = 45)
private String login;
#Column(name = "name", nullable = false, length = 45)
private String name;
#Column(name = "surname", nullable = false, length = 45)
private String surname;
/* getters and setters*/
}
My hibernate-annotation.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/web-database</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Mapping with model class containing annotations -->
<mapping class="entities.UserH"/>
</session-factory>
</hibernate-configuration>
Method that should get users:
public List<UserH> getAllUsers() {
try (Session session = HibernateUtils.getSessionAnnotationFactory().getCurrentSession()) {
session.beginTransaction();
Query<UserH> usersQuery = session.createQuery("from entities.UserH", UserH.class);
List<UserH> usersList = usersQuery.getResultList();
session.getTransaction().commit();
return usersList;
}
}
As I mentioned - it works ok with normal app, but not with Tomcat. I added all available elements to web artifacts, but it didn't help. I even tried to add JPA support with persistance.xml, but still with no luck.
What else could be the problem?
edit: My HibernateUtils class:
public class HibernateUtils {
private static SessionFactory sessionAnnotationFactory;
private static SessionFactory buildSessionAnnotationFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null)
sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
}
Maybe this is not a proper answer fot my question, but this is what actually worked for me. I replaced hibernate with JPA configuration + hibernate.
So instead of using hibernate-annotation.cfg.xml + Session I used persistance.xml + EntityManager:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>entities.UserH</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/web-database"/>
<property name="javax.persistence.jdbc.user" value="Admin"/>
<property name="javax.persistence.jdbc.password" value="password2#"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
getEntityManager:
public static EntityManager getEntityManager() {
EntityManager entityManager = Persistence
.createEntityManagerFactory("NewPersistenceUnit")
.createEntityManager();
return entityManager;
}
getAllUsers:
public List<UserH> getAllUsers() {
EntityManager entityManager = HibernateUtils.getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<UserH> usersQuery = entityManager.createQuery("from UserH ", UserH.class);
List<UserH> usersList = usersQuery.getResultList();
transaction.commit();
entityManager.close();
return usersList;
}
However, I still don't understand why this configurations works while hibernate alone didn't. Any comments/suggestions would be appreciated.
You should just change your query to reference only the class name:
session.createQuery( "FROM UserH", UserH.class )
The only time the package is important would be when you're defining entities as inner classes.
For those cases, you'd need to use the full class name, com.c.SomeOutterClass$MyEntity. Another alternative is to change the #Entity annotation so that it includes the name attribute so you explicitly name your entity class:
public class SomeOutterClass {
#Entity(name = "MyEntity")
public static class MyEntity {
}
}

JPA Eclipselink Multitenant, table doesn't exist error

i'm trying to make a simple multitenant example to run, using Eclipselink 2.5.2, and MySQL.
When trying to persist an entity asigned to a tenant id, mysql server throws an error: "Table 'jpatest.tenant1_userdata' doesn't exist". (userdata being the entity, jpatest the database name, and tenant1 the tenant-id)
The table indeed doesn't exist, the database jpatest do exist. I was expecting eclipselink to autogenerate the tables each time i try to persist with a new tenant id.
So the question would be:
How can i force Eclipselink to create the tables?
If that is not possible; How can i create tables at runtime?
Here's the code:
Entity:
#Entity
#Table(name = "userdata")
#Multitenant(value = MultitenantType.TABLE_PER_TENANT)
#TenantTableDiscriminator(type = TenantTableDiscriminatorType.PREFIX, contextProperty = "tenant-id")
public class UserData implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private static final long serialVersionUID = 1L;
private String name;
.
.
.
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="MultiTeanantTest" transaction-type="RESOURCE_LOCAL">
<class>UserData</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpatest" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-database-schemas" value="true"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Main class:
public class Main {
public static void main(String[] args) {
UserData ud = new UserData();
ud.setNombre("John);
Map properties = new HashMap<>();
properties.put("tenant-id", "tenant1");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MultiTeanantTest", properties );
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(ud);
em.getTransaction().commit();
}
}
Hope someone can give me a tip in what i'm doing wrong.
DDL generation will not be supported in a Multitenant Scenario by Eclipselink.
Refer to this link for more information, https://wiki.eclipse.org/EclipseLink/DesignDocs/Multi-Tenancy/TablePerTenant

org.apache.openjpa.persistence.ArgumentException while running the main class

I using using maven simple java project
Im getting the following exception while running the main class
346 INFO [main] openjpa.Runtime - OpenJPA dynamically loaded the class
enhancer. Any classes that were not enhanced at build time
will be enhanced when they are loaded by the JVM.
414 INFO [main] openjpa.Runtime - Starting OpenJPA 2.3.0
<openjpa-2.3.0-r422266:1540826 fatal user error>
org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the data
source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties are available
in the configuration: "org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#442ce698".
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:72)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:849)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:602)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1518)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:535)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:460)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:121)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:967)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:958)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:643)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at org.msharma.JpaImpl.main(JpaImpl.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
My entity clas
#Entity(name ="customer")
public class Customer implements Serializable{
#Id
#Column(name ="cust_id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
#Column(name = "first_name",length = 50, nullable = false)
private String firstName;
#Column(name = "last_name",length = 50)
private String lastName;
// By default column name is same as attribute name
private String street;
private String appt;
private String city;
#Column(name = "zip_code",length = 50, nullable = false)
private String zipCode;
#Column(name = "cust_type",length = 50, nullable = false)
private String custType;
#Version
#Column(name = "last_updated_time")
private Date updatedTime;
public Customer(){}
// getters and setters
}
This is my persistence.xml
<?xml version="1.0"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>org.somepack.Customer</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:mysql://localhost:3306/test"/>
<property name="openjpa.ConnectionDriverName"
value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="root"/>
<property name="openjpa.ConnectionPassword" value="pass"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
</persistence>
This is my mainClass
public static void main(String[] args) {
try {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("testjpa");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Customer customer = new Customer();
//set the properties to the customer object
entityManager.persist(customer);
entityTransaction.commit();
entityManager.close();
entityManagerFactory.close();
}
catch (Exception e){
e.printStackTrace();
}
}
How do I resolve the problem .
I have openjpa, openjpa-persistence-jdbc, mysql-connector-java dependencies in my POM.xml
and my persistence.xml is under src/main/resources
As you said your persistence.xml is under src/main/resources so may be it is unable to read it
you must place it under src/main/resources/META-INF
One more thing add
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
to your persistence.xml.
If you add the openjpa.jdbc.SynchronizeMappings property as shown below OpenJPA will auto-create all your tables, all your primary keys and all foreign keys exactly to match your objects
Add <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> to your persistence.xml:
<?xml version="1.0"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>org.somepack.Customer</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:mysql://localhost:3306/test"/>
<property name="openjpa.ConnectionDriverName"
value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="root"/>
<property name="openjpa.ConnectionPassword" value="pass"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>

How do I create an instance of my EntityManagerFactory by using my persistence.xml?

I am creating a backend application using Spring, Hibernate and JPA.
Currently the application test pass but I get a warning:
WARN: HHH000436: Entity manager factory name (JpaPersistenceUnit) is already registered.
I think the reason for this is that I defined my JpaPersistenceUnit in the persistence.xml and I also create one in my dao class. If this is the case I need to find a way to get my JpaPersistenceUnit from the persistence.xml without creating it (again). But I don't know how...
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="JpaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="groepD"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/groepd"/>
<property name="hibernate.connection.username" value="groepD"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
This is my generic dao class:
public interface GenericDao<E, ID extends Serializable> {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
public void add(E entity);
public void remove(E entity);
public void update(E entity);
public E findById(ID id);
public List<E> findAll();
}
This is the specific dao class:
public interface TripDao extends GenericDao<Trip,Integer> {
}
And this is an implementation of the dao class:
#Repository
public class TripDaoImpl implements TripDao {
protected EntityManager entityManager;
public TripDaoImpl() {
entityManager = emf.createEntityManager();
}
#Override
#Transactional
public void add(Trip entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
....
}
This is the entity:
#Entity
#Table(name = "T_TRIP")
public class Trip {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
private String name;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_ADMINS",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> admins;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_PARTICIPANT",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> invitedUsers;
#NotNull
private Boolean privateTrip;
#NotNull
private Boolean published;
#Enumerated(EnumType.STRING)
private TripType type;
#NotNull
private Integer nrDays;
#NotNull
private Integer nrHours;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "tripId")
private Set<Stop> stops;
public Trip(){
initLists();
}
private void initLists(){
this.admins = new HashSet<User>();
this.invitedUsers = new HashSet<User>();
this.stops = new HashSet<Stop>();
}
public void addStop(Stop stop) {
stops.add(stop);
}
public boolean removeStop(Stop stop) {
if (stops.size() > 1 && stops.contains(stop)) {
stops.remove(stop);
return true;
} else {
return false;
}
}
...More getters and setters...
}
If someboby could tell me how to to fix the warning that would be very helpfull.
first: (in you applicationContext.xml)
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation"
value="classpath:persistence.xml">
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="loadTimeWeaver"> <!-- 运行时植入 -->
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
next:(update you code)
remove :EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
next: you can get the class EntityManager by this
#PersistenceContext
protected EntityManager entityManager;
ps:sorry my english is so poor,
wish helpfull for you!

Categories

Resources