Java Hibernate attributeoverride annotation not working? - java

Hi I am currently learning Hibernate and I am stuck on a problem where I am trying to override the column name from address to home address and office address. I commented out all office-address code, but the column in database are still "CITY_NAME", "STREET_NAME" and etc.
Could someone please explain this, thanks.
Address.java
package org.zm.javabrain.dto;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="STREET_NAME")
private String stree;
#Column(name="CITY_NAME")
private String city;
#Column(name="STATE_NAME")
private String state;
#Column(name="ZIP_NAME")
private String zip;
public String getStree() {
return stree;
}
public void setStree(String stree) {
this.stree = stree;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
this is UserDetails.java
package org.zm.javabrain.dto;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity // change the name of the entity
#Table(name="USER_DETAILS") // change the name of the table
public class UserDetails implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String username;
private Date joinedDate;
private String description;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="street",column=#Column(name="HOME_STREET_NAME")),
#AttributeOverride(name="city",column=#Column(name="HOME_CITY_NAME")),
#AttributeOverride(name="state",column=#Column(name="HOME_STATE_NAME")),
#AttributeOverride(name="zip",column=#Column(name="HOME_ZIP_NAME"))})
private Address homeAddress;
// #Embedded
// #AttributeOverrides({
// #AttributeOverride(name="street",column=#Column(name="OFFICE_STREET_NAME")),
// #AttributeOverride(name="city",column=#Column(name="OFFICE_CITY_NAME")),
// #AttributeOverride(name="state",column=#Column(name="OFFICE_STATE_NAME")),
// #AttributeOverride(name="zip",column=#Column(name="OFFICE_ZIP_NAME"))})
// private Address officeAddress;
//
// public Address getOfficeAddress() {
// return officeAddress;
// }
// public void setOfficeAddress(Address officeAddress) {
// this.officeAddress = officeAddress;
// }
public Date getJoinedDate() {
return joinedDate;
}
public void setJoinedDate(Date joinedDate) {
this.joinedDate = joinedDate;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
This is driver class
package org.zm.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.zm.javabrain.dto.Address;
import org.zm.javabrain.dto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
Address addr = new Address();
addr.setCity("chicago");
addr.setState("IL");
addr.setStree("Michigen Ave");
addr.setZip("55414");
Address officeAddr = new Address();
officeAddr.setCity("minneapolis");
officeAddr.setState("Washington Ave");
officeAddr.setState("MN");
officeAddr.setZip("55455");
user.setUsername("11111");
user.setHomeAddress(addr);
// user.setOfficeAddress(officeAddr);
user.setJoinedDate(new Date());
user.setDescription("this is a description");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}

I cannot tell you if Hibernate Session supports the AttributeOverride feature or not. The problem is, I guess, Hibernate is mixing two different technologies that are trying to solve the same problem, and that is confusing for new users trying to learn. Hibernate can be used as
Legacy (Native) ORM , and
JPA (Java Persistence API) implementation
As I can see from your posted code example that you are using JPA annotations. All annotations, classes and properties having the package structure of javax.persistence are JPA specific. So my advice is, either configure your persistence the Hibernate way or the JPA way, and don't mix.
If you want to map your entities the JPA way, do the following:
Put your configuration information in the file persistence.xml instead of in the hibernate.cfg.xml. The file should be under META-INF folder of your source directory. If you are using Maven put it under src/main/resources/META-INF directory. The file should look like:
<persistence 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"
version="2.1">
<persistence-unit name="yourPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>org.zm.javabrain.dto.UserDetails</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="..." />
<property name="javax.persistence.jdbc.url" value="..." />
<property name="javax.persistence.jdbc.user" value="..." />
<property name="javax.persistence.jdbc.password" value="..." />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>
replace the ... with correct database information.
In your test class (HibernateTest) do the following instead of SessionFactory / Session:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit;
em.close();
emf.close();
You can also read:
Hibernate User Guide
Java Persistence API Tutorials
JPA 2.1 Specification
Hopefully, it helps.

Related

Error: Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.demo.model.Contact

Before you mark it duplicate, Please read below :
I have already tried all the given answers in similar Questions-
My Import for #Entity is correct:import javax.persistence.Entity;
Mapping for entity in hibernate.cfg.xml is present
Class is mapped from pkg level:"com.hibernate.demo.model.Contact"
AnnotationConfiguration is also not resolving the issue.
All the other second to third best answers were tried too.
Background : I have created a Spring-boot project and I am trying to learn hibernate, I am using H2 db and I am facing >Unknown entity: com.hibernate.demo.model.Contact
I have verified that mapping of the class is present in
hibernate.cfg.xml
<mapping class="com.hibernate.demo.model.Contact"/>
I have also verified that mapping has full pkg level mapping path
This is the my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./data/contactmgr</property>
<property name="connection.username">sa</property>
<property name="hibernate.default_schema">PUBLIC</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.hibernate.demo.model.Contact"/>
</session-factory>
</hibernate-configuration>
my Application.java Main class :-
package com.hibernate.demo;
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry;
import com.hibernate.demo.model.Contact;
public class Application {
//Session factory
private static final SessionFactory sessionFactory = buildSesssionFactory();
public static void main(String[] args) throws Exception {
System.out.println("Session factory");
Contact contact = new Contact.ContactBuilder("Bob", "Marley").withEmail("bob.nik#gmail.com").withPhone(5859789733L).build();
//Open a Session
System.out.println("Open a Session");
Session session = sessionFactory.openSession();
//Begin a Transaction
System.out.println("Begin a Transaction");
session.beginTransaction();
//Use the session to save the contact
System.out.println("Use the session to save the contact");
try{
session.save(contact);
} catch(Exception e) {
// Close the session
shutdown();
throw e;
}
//Commit the transaction
System.out.println("Commit the transaction");
session.getTransaction().commit();
// Close the session
System.out.println("Close the session");
session.close();
}
private static SessionFactory buildSessionFactory()
{
try
{
if (sessionFactory == null)
{
Configuration configuration = new Configuration().configure(Application.class.getResource("/hibernate.cfg.xml"));
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
I am doing all the right things, I have already checked that the
#Entity import has right package
package com.hibernate.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
#Column
private Long phone;
public Contact() {
}
public Contact(ContactBuilder contactBuilder) {
this.firstName = contactBuilder.firstName;
this.lastName = contactBuilder.lastName;
this.email = contactBuilder.email;
this.phone=contactBuilder.phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
#Override
public String toString() {
return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", phone=" + phone + "]";
}
public static class ContactBuilder {
private String firstName;
private String lastName;
private String email;
private Long phone;
public ContactBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public ContactBuilder withEmail(String email) {
this.email = email;
return this;
}
public ContactBuilder withPhone(Long phone) {
this.phone = phone;
return this;
}
public Contact build() {
return new Contact(this);
}
}
}
configuration.addAnnotatedClass(Contact.class);
resolves the issue, which is weird because it means
<mapping class="com.contact.model.Contact"/>
is not doing it for you. I don't like xml configuration anyways, good riddance.

Setting up JPA persistence with exception No persistence provider for EntityManager

I am overlooking some aspect of the setup but I don't know where to look. Eclipse, Tomcat, and MySQL. In the servlet I have an exception: No Persistence provider for EntityManager named EmployeeService. MySQL server is running and I configured a connection for the project. I have eclipselink jar library in the build path. What can I check to get it working?
Employee.java
package servlet;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private String name;
private double salary;
public Employee() { }
public Employee(int id){ this.id = id; }
public int getId() { return this.id; }
public void setId(int id) { this.id = id; }
public String getName(){ return this.name; }
public void setName(String name){ this.name = name; }
public double getSalary(){ return salary; }
public void setSalary(double salary){ this.salary = salary; }
public String toString(){ return "Employee: " + name; }
}
EmployeeService.java
package servlet;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public class EmployeeService {
protected EntityManager em;
public EmployeeService(EntityManager em){
this.em = em;
}
public Employee createEmployee(int id, String name, Double salary){
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
public List<Employee> findAllEmployees(){
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e", Employee.class);
return query.getResultList();
}
}
Relevant servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");
EntityManager em = emf.createEntityManager();
EmployeeService service = new EmployeeService(em);
String name = request.getParameter("name");
em.getTransaction().begin();
Employee emp = service.createEmployee(158, name, 279445.00);
em.getTransaction().commit();
System.out.println(emp);
List<Employee> list = service.findAllEmployees();
for(Employee e : list){
System.out.println(e);
}
}
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="4_WEB_JPA" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>servlet.Employee</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/company"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
You can initiate EntityManagerFactory by
EntityManagerFactory emf = Persistence.createEntityManagerFactory("4_WEB_JPA");
because your persistent unit named 4_WEB_JPA in your persistent.xml.

hibernate not recognising my entities

I am trying to learn hibernate and i'm having a problem with hibernate annotations, the thing is that hibernate doesn't seam to recognise my entity User
package com.mycompanyname.myapp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_ID")
private Long userId;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="BIRTH_DATE")
private Date birthDate;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name="CREATED_DATE")
private Date createdDate;
#Column(name="CREATED_BY")
private String createdBy;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
this is my main
package com.mycompanyname.myapp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import com.mycompanyname.myapp.User;
public class Application {
public static void main(String[] args) {
// A SessionFactory is set up once for an application!
SessionFactory sessionFactory =null;
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
//session.close();
}
}
this is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="HibernateUtil">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">database</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/financialanalysis</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<mapping class="com.mycompanyname.myapp.User"/>
</session-factory>
</hibernate-configuration>
this exception keeps popping out
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.mycompanyname.myapp.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.mycompanyname.myapp.Application.main(Application.java:32)
so what am i doing wrong ?
I think there is an issue with the way you configure SessionFactory. I created a sample application based on the source code you have provided. I suspect there is something wrong with this line.
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
So I would take a different approach to configure session factory like this.
SessionFactory sessionFactory =null;
try {
Configuration configuration = new Configuration();
configuration.configure();
final ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(registry);
}
catch (Exception e) {
e.printStackTrace();
sessionFactory.close();
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
session.close();
Looking at the source code configuration.configure() method also finds the default hibernate.cfg.xml file on the classpath as new StandardServiceRegistryBuilder().configure() does. With these configurations in place now you should be able to persist/load/update entities without any issue.
I tested this configuration with a quick and dirty sample application using Hibernate 4.0.
Just use this to build a session factory
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
It works for Hibernate 4 and Hibernate 5. This code has a deprecation in Hibernate 4, but this deprecation is removed in Hibernate 5.
configure your User class like-
Configuration cfg=new Configuration();
cfg.addAnnotatedClass(com.mycompanyname.myapp.User.class);
cfg.configure();
hope it help.

Repeated column in mapping for entry error

I am doing a simple hibernate program in which I use Attribute override and Embedded object keys and I got this error:
Exception in thread "main" org.hibernate.MappingException: Repeated
column in mapping for entity: com.hibernate.Model.Employee column:
pincode (should be mapped with insert="false" update="false")
Employee.java
package com.hibernate.Model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String LastName;
private String email;
private String phoneNo;
#Embedded
#AttributeOverrides({
#AttributeOverride (name="City" , column=#Column(name="OFFICE_CITY")),
#AttributeOverride (name="State", column=#Column(name="OFFICE_STATE")),
#AttributeOverride (name="Country", column=#Column(name="OFFICE_COUNTRY")),
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))})
private Address officeAddress;
#Embedded
private Address homeAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
Address.java
package com.hibernate.Model;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String City;
private String State;
private String Country;
private String pincode;
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.jsp
package com.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.Model.Address;
import com.hibernate.Model.Employee;
public class HibernateTest {
public static void main(String[] args) {
Employee emp = new Employee();
Address addr=new Address();
emp.setFirstName("Vikas");
emp.setLastName("Bhardwaj");
emp.setEmail("bhardwajvikas93#gmail.com");
emp.setPhoneNo("9741178304");
addr.setCity("MEHRE");
addr.setCountry("INDIA");
addr.setState("HIMACHAL");
addr.setPincode("174305");
emp.setHomeAddress(addr);
Address addr2 = new Address();
addr2.setCity("Bangalore");
addr2.setCountry("INDIA");
addr2.setState("KARNATKA");
addr2.setPincode("560008");
emp.setOfficeAddress(addr2);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session ssn = sf.openSession();
ssn.beginTransaction();
ssn.save(emp);
ssn.getTransaction().commit();
ssn.close();
}
}
cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
<property name="connection.username">root</property>
<property name="connection.password">vikas</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="com.hibernate.Model.Employee"/>
<mapping class="com.hibernate.Model.Address"/>
</session-factory>
</hibernate-configuration>
In this program by embedable, I am printing both member variables in one table.
The task is with address class, I am printing two addresses. One is for home address and one is for office address by using AttributeOverrides but it gives me the error mentioned above.
You need to specify a valid property name pincode
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))
need to change to
#AttributeOverride (name="pincode", column=#Column(name="OFFICE_PINCODE"))
Try to specify #AttributeOverrides for homeAddress, if it will not help.

TomEE + OpenJPA: Error creating EntityManager using container managed DataSource

I'm trying to configure an example JPA application in Eclipse, and deploy it to TomEE+. The datasource is container managed. I keep seeing the following error when attempting to create the EntityManager:
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#414793b4".
Any idea what is wrong with this configuration?
Below is the code.
tomee.xml
<tomee>
<Resource id="jdbc/MyAppDS" type="DataSource">
JdbcDriver com.microsoft.sqlserver.jdbc.SQLServerDriver
JdbcUrl jdbc:sqlserver://localhost:1433/db_dev
UserName user
Password password
JtaManaged true
DefaultAutoCommit false
</Resource>
</tomee>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0">
<persistence-unit name="Simplest" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>jdbc/MyAppDS</jta-data-source>
<class>social.Media</class>
</persistence-unit>
</persistence>
Media.java
package social;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "media")
public class Media {
#Id
#Column(name = "id")
private String id;
private String description;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Controller.java
package social;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Controller {
#Inject private Media media;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Simplest");
EntityManager em = emf.createEntityManager(); // exception reported on this line
.
.
.
return media.getDescription();
}
}
You are using JTA-managed Entity Manager Factory, I think that instead of manual creation of EntityManagerFactory you should let application server do it for you, like this in controller:
#Path("/hello")
public class Controller {
#PersistenceContext(unitName="Simplest")
private EntityManager em;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
// get Media from database - replace with your own code
Media media = em.find(Media.class, "1");
return media.getDescription();
}
}

Categories

Resources