guys please help me for solve this error, it's been 4 days, this problem hasn't been solved.
this is my Entity Class code :
package mybengkel;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author rhmtsaepuloh
*/
#Entity
#Table(name = "employee")
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByUsername", query = "SELECT e FROM Employee e WHERE e.username = :username"),
#NamedQuery(name = "Employee.findByPassword", query = "SELECT e FROM Employee e WHERE e.password = :password")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Employee(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "mybengkel.Employee[ id=" + id + " ]";
}
}
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="MyBengkelPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>/Users/rhmtsaepuloh/Downloads/mysql-connector-java-8.0.18/mysql-connector-java-8.0.18.jar</jar-file>
<class>mybengkel.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/oop?serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
and Main class java :
package mybengkel;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author rhmtsaepuloh
*/
public class MyBengkel {
public static void main(String[] args) {
EntityManager em;
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("MyBengkelPU");
em = emf.createEntityManager();
em.getTransaction().begin();
Employee e = new Employee();
e.setUsername("haha");
e.setPassword("hehe");
em.persist(e);
em.getTransaction().commit();
}
}
the problem is when I run the program found error code :
[EL Info]: 2019-11-28 16:07:45.916--ServerSession(347978868)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2019-11-28 16:07:46.813--ServerSession(347978868)--file:/Volumes/Data/Perkuliahan/OOP/NetBeans/MyBengkel/build/classes/_MyBengkelPU login successful
[EL Warning]: metamodel: 2019-11-28 16:07:46.859--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
Exception in thread "main" java.lang.IllegalArgumentException: Object: mybengkel.Employee[ id=null ] is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at mybengkel.MyBengkel.main(MyBengkel.java:29)
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:111: The following error occurred while executing this line:
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:68: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I try this on netbeans 11.1 and mysql connector java 8.0.18 Please help me to fix it guys... Thanks before
Related
I am attempting to write a rest API to interface with a MariaDB. I feel like I am most of the way there however I am recieving the following error:
java.lang.IllegalArgumentException: Unknown entity: Models.User
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:808)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at test.Application.addUser(Application.java:40)
at test.Application.main(Application.java:18)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:542)
at java.base/java.lang.Thread.run(Thread.java:834)
I imagine that this is because I have incorrectly configured the user class in the persistence.xml file in resources/META-INF. Below are the relavent inter relating files:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="potholeAPI" transaction-
type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Models.User</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/PotholeDB?
useUnicode=true&useJDBCCompliantTimezoneShift
=true&useLegacyDate
timeCode=false&serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
</properties>
</persistence-unit>
User.java
package Models;
import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
#Table(appliesTo = "Users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id", unique = true)
private int id;
#Column(name = "name", unique = true)
private String name;
#Column(name = "created_date")
private int created_date;
getters and setters....
and the main and driver for my testing
Application.java
package test;
import Models.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#SpringBootApplication
public class Application {
private static EntityManagerFactory ENTITY_MANAGER_FACTORY =
Persistence.createEntityManagerFactory("potholeAPI");
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
addUser(1, "jim");
addUser(2, "bob");
getUser(1);
getUsers();
ENTITY_MANAGER_FACTORY.close();
}
public static void addUser(int id, String name) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Date date = new Date();
try {
et = em.getTransaction();
et.begin();
User user = new User();
user.setId(id);
user.setName(name);
user.setCreated_date(date.getDate());
em.persist(user);
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
public static void getUser(int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id = :userID";
TypedQuery<User> tq = em.createQuery(query, User.class);
tq.setParameter("userID", id);
User user = null;
try {
user = tq.getSingleResult();
System.out.println(user.getName() + " ");
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
public static void getUsers() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id IS NOT NULL";
TypedQuery<User> tq = em.createQuery(query, User.class);
List<User> users;
try {
users = tq.getResultList();
users.forEach(user-> System.out.println(user.getName()+ " "));
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
}
My suspicion is that I screwed up the xml file however I am new to spinning up an API like this so I am not fully confident.
Tablename is 'User',so User.java->#Table(appliesTo = "Users") should be #Table(appliesTo = "User")
I've created 2 entity classes:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "fr")
public class FR {
#Id
#Column(name = "id")
private String id;
#Column(name = "pid")
private String pId;
#Column(name = "pname")
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
and
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ar")
public class AR {
#Id
#Column(name = "id")
private String id;
#Column(name = "value1")
private String value1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
}
and I'm trying to join these tables to fetch the record.
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123");
but getting an exception:
org.hibernate.QueryException: Unable to resolve path [FR.id], unexpected token [FR] [from entities.FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123]
and when I'm removing FR from the query
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where id=123 or pId=123");
getting another exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from entities.FR left join AR on FR.pId = AR.id where id=123 or pId=123]
I'm in a learning stage of Hibernate and don't know what to do now.
If you've any other info regarding Left Join or the other Joins then please share that too.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/examples?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root#123</property>
<property name="hibernate.show_sql">true</property>
<mapping class="entities.FR"/>
<mapping class="entities.AR"/>
</session-factory>
</hibernate-configuration>
Main Class
package hibernate.joins;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateJoins {
public static void main(String[] args) {
SessionFactory sessionFactory = getSessionFactory();
Session session = sessionFactory.openSession();
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id and ( FR.id=123 or FR.pId=123 )");
List list = qry.list();
list.forEach(System.out::println);
session.close();
sessionFactory.close();
}
public static SessionFactory getSessionFactory () {
SessionFactory sessionFactory = new Configuration().configure("configurations/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
}
Since you are using ON clause in your query, therefore, you can not to use where clause separately. Just keep on adding the condition using AND or OR clause(whichever is applicable)
i created a project on netbeans and add jpa , but when i run this project i take this error. I use netbeans ide.
[EL Info]: 2017-11-05 00:01:05.271--ServerSession(1276666395)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2017-11-05 00:01:05.451--ServerSession(1276666395)--file:/C:/Users/kB/Documents/NetBeansProjects/JavaApplication11/build/classes/_JavaApplication11PU login successful
[EL Warning]: 2017-11-05 00:01:20.582--ServerSession(1276666395)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Table 'room' already exists
Error Code: 1050
Call: CREATE TABLE room (room_id INTEGER NOT NULL, room_name VARCHAR(255), PRIMARY KEY (room_id))
Query: DataModifyQuery(sql="CREATE TABLE room (room_id INTEGER NOT NULL, room_name VARCHAR(255), PRIMARY KEY (room_id))")
[EL Warning]: 2017-11-05 00:01:35.687--ServerSession(1276666395)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Table 'sequence' already exists
Error Code: 1050
Call: CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))
Query: DataModifyQuery(sql="CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))")
[EL Warning]: 2017-11-05 00:01:35.816--UnitOfWork(190868662)--java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:278)
at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:71)
at org.eclipse.persistence.sequencing.DefaultSequence.getGeneratedVector(DefaultSequence.java:163)
at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:468)
at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:361)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:320)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:486)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4290)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at javaapplication11.JavaApplication11.main(JavaApplication11.java:29)
C:\Users\kB\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 31 seconds)
It is my Entity Class
package javaapplication11;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* #author kB
*/
#Entity
#Table(name="room")
public class NewEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "room_id")
private int id;
#Column(name = "room_name")
private String name;
public NewEntity() {
}
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;
}
#Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + this.id;
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final NewEntity other = (NewEntity) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
#Override
public String toString() {
return super.toString(); //To change body of generated methods, choose Tools | Templates.
}
}
And it is main class
package javaapplication11;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author kB
*/
public class JavaApplication11 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplication11PU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
NewEntity x = new NewEntity();
x.setName("anan");
em.persist(x);
em.getTransaction().commit();
em.close();
emf.close();
}
}
Lastly it is my 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="JavaApplication11PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>javaapplication11.NewEntity</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/felek"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Is this the whole code?
Because the end of stack trace points to JavaApplication11.java:29, which is } sign of your main, which is weird.
I am writing a Java project that uses Hibernate ORM and Spring Framework. Right now, when I add a POJO class, I need to modify my hibernate.cfg.xml file, which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="somepackage.class1"/>
<mapping class="somepackage.class2"/>
<!-- etc. -->
</session-factory>
</hibernate-configuration>
Then, I create an annotation-based class. I heard that I could avoid adding per-class mappings in hibernate.cfg.xml if I used proper Hibernate annotations. How can I modify a class to avoid the mappings in an XML file? Here is my example POJO file, generated by NetBeans:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package somepackage.pojo;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author D
*/
#Entity
#Table(name = "ACCOUNT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Account.findAll", query = "SELECT a FROM Account a"),
#NamedQuery(name = "Account.findByLogin", query = "SELECT a FROM Account a WHERE a.login = :login"),
#NamedQuery(name = "Account.findByPassword", query = "SELECT a FROM Account a WHERE a.password = :password")})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "LOGIN", nullable = false, length = 100)
private String login;
#Size(max = 128)
#Column(name = "PASSWORD", length = 128)
private String password;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
private Collection<Comment> commentCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
private Collection<Article> articleCollection;
public Account() {
}
public Account(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlTransient
public Collection<Comment> getCommentCollection() {
return commentCollection;
}
public void setCommentCollection(Collection<Comment> commentCollection) {
this.commentCollection = commentCollection;
}
#XmlTransient
public Collection<Article> getArticleCollection() {
return articleCollection;
}
public void setArticleCollection(Collection<Article> articleCollection) {
this.articleCollection = articleCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (login != null ? login.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Account)) {
return false;
}
Account other = (Account) object;
if ((this.login == null && other.login != null) || (this.login != null && !this.login.equals(other.login))) {
return false;
}
return true;
}
#Override
public String toString() {
return "somepackage.pojo.Account[ login=" + login + " ]";
}
}
I'd suggest you export the hibernate configuration to the spring configuration because of the flexibility that spring provides. Your concern is to not declare the class in the configuration every time you create a new entity. Using spring configuration you can do the following. (packagestoscan property)
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.baeldung.spring.persistence.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
Ref: http://www.javacodegeeks.com/2013/05/hibernate-3-with-spring.html
I'm trying to figure out how to use #PersistenceUnit as I've read it's a much better solution than #PersistenceContext. The trouble is.... I can't figure out how to get it to work properly...
#Controller
public class Content {
#PersistenceUnit(unitName = "CMTPU")
public EntityManagerFactory emf;
public EntityManager em = emf.createEntityManager();
#RequestMapping(value={"/content/edit*"}, method=RequestMethod.GET)
public ModelAndView edit(Model model) {
ModelAndView mv = new ModelAndView();
mv.setViewName("content/edit");
//get symbols
List<Symbol> symbols = em.createNamedQuery("Symbol.findAll").getResultList();
mv.addObject(symbols);
return mv;
}
}
My app loaded before I added the //get symbols section and the EntityManager stuff. Now I'm seeing the error SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NullPointerException
I've read that I need to define a unitName, but then I'm looking at this documentation and it doesn't show that being done.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="CMTPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>CMT_DEV</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I'm having trouble determining what I'm doing wrong.
update
My model defines the database and all of that as seen below. Do I even need a persistence.xml?
package com.fettergroup.cmt.models;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "symbol", catalog = "DATABASE1", schema = "dbo")
#NamedQueries({
#NamedQuery(name = "Symbol.findAll", query = "SELECT s FROM Symbol s"),
#NamedQuery(name = "Symbol.findById", query = "SELECT s FROM Symbol s WHERE s.id = :id"),
#NamedQuery(name = "Symbol.findBySymbol", query = "SELECT s FROM Symbol s WHERE s.symbol = :symbol"),
#NamedQuery(name = "Symbol.findByHtmlNumber", query = "SELECT s FROM Symbol s WHERE s.htmlNumber = :htmlNumber"),
#NamedQuery(name = "Symbol.findByHtmlName", query = "SELECT s FROM Symbol s WHERE s.htmlName = :htmlName"),
#NamedQuery(name = "Symbol.findByAsciiDec", query = "SELECT s FROM Symbol s WHERE s.asciiDec = :asciiDec"),
#NamedQuery(name = "Symbol.findByAsciiHex", query = "SELECT s FROM Symbol s WHERE s.asciiHex = :asciiHex")})
public class Symbol implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Short id;
#Size(max = 10)
#Column(name = "symbol")
private String symbol;
#Size(max = 10)
#Column(name = "html_number")
private String htmlNumber;
#Size(max = 10)
#Column(name = "html_name")
private String htmlName;
#Size(max = 10)
#Column(name = "ascii_dec")
private String asciiDec;
#Size(max = 10)
#Column(name = "ascii_hex")
private String asciiHex;
public Symbol() {
}
public Symbol(Short id) {
this.id = id;
}
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getHtmlNumber() {
return htmlNumber;
}
public void setHtmlNumber(String htmlNumber) {
this.htmlNumber = htmlNumber;
}
public String getHtmlName() {
return htmlName;
}
public void setHtmlName(String htmlName) {
this.htmlName = htmlName;
}
public String getAsciiDec() {
return asciiDec;
}
public void setAsciiDec(String asciiDec) {
this.asciiDec = asciiDec;
}
public String getAsciiHex() {
return asciiHex;
}
public void setAsciiHex(String asciiHex) {
this.asciiHex = asciiHex;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Symbol)) {
return false;
}
Symbol other = (Symbol) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.project1.models.Symbol[ id=" + id + " ]";
}
}
use only
#Controller
public class Content {
#PersistenceContext(unitName = "CMTPU")
public EntityManager em;
The entity manager should be controlled by spring.
This ins an example, it uses hiberante as persistence provider, but I think you can adapt it.
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="myPersistenceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
sample persistance unit, that works with that configuration
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>