I try to run a basic application with hibernate and jpa, but now I'm stuck on this exception when running app...Here's the code and erro below:
java.lang.IllegalArgumentException: Not an entity: class pka.EclipseJPAExample.domain.Employee
at org.hibernate.ejb.metamodel.MetamodelImpl.entity(MetamodelImpl.java:158)
at org.hibernate.ejb.criteria.QueryStructure.from(QueryStructure.java:136)
at org.hibernate.ejb.criteria.CriteriaQueryImpl.from(CriteriaQueryImpl.java:177)
at pka.EclipseJPAExample.jpa.JpaTest.createEmployees(JpaTest.java:47)
at pka.EclipseJPAExample.jpa.JpaTest.main(JpaTest.java:33)
JpaTest.java:
public class JpaTest {
private EntityManager manager;
public JpaTest(EntityManager manager) {
this.manager = manager;
}
/**
* #param args
*/
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager manager = factory.createEntityManager();
JpaTest test = new JpaTest(manager);
EntityTransaction tx = manager.getTransaction();
tx.begin();
try {
test.createEmployees();
} catch (Exception e) {
e.printStackTrace();
}
tx.commit();
test.listEmployees();
System.out.println(".. done");
}
private void createEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
int numOfEmployees = manager.createQuery(query).getResultList().size();
if (numOfEmployees == 0) {
Department department = new Department("java");
manager.persist(department);
manager.persist(new Employee("Jakab Gipsz",department));
manager.persist(new Employee("Captain Nemo",department));
}
}
private void listEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
List<Employee> resultList = manager.createQuery(query).getResultList();
for (Employee next : resultList) {
System.out.println("next employee: " + next);
}
}
}
and persistence.xml:
....<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testowa" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="enchantsql" />
<property name="hbm2ddl.auto" value="create" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>....
Could you point where is the problem?
EDIT:
I forgot to paste Employee class...so here it is below:
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToOne
private Department department;
public Employee() {}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
public Employee(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}
}
As you can see it is mapped.
Make sure #Entity annotation in your entity. You also need to configure an entity in persistence.xml
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<class>pka.EclipseJPAExample.domain.Employee</class>
If you have numerous ENTITY classes in your application, adding an entry for every entity in "persistence.xml" won't be a good choice.
Instead, create your own data source bean using Custom AutoConfiguration.
Use LocalContainerEntityManagerFactoryBean inside dataSource bean Creation method.
Here, you need to define
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new
LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPackagesToScan("org.springframework.boot.entities");
This package is the location where all entity classes have been saved.
Thus no need to define every single entry for Entity classes at "persistence.xml".
Prefer Spring-based Scanning.
Related
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 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.
I am making a sample application using hibernate and h2 database. I have an entity class (actually more than 1, but let's start with making it work for 1 of them), which looks like that:
package ~path.examples.testjpa.domain;
import javax.persistence.*;
import java.util.*;
/**
* Created by Me on 2015-04-20.
*/
#Entity
#Table(name= "Persons")
public class Person {
#Id
#Column(nullable= false)
#GeneratedValue(strategy = GenerationType.AUTO)
protected int persId;
#Column(nullable= false, length = 50)
private String firstName;
#Column(nullable= false, length = 50)
private String surname;
#Column(nullable= true, length = 50)
private String emailAddress;
#OneToOne
private Account account;
#OneToMany(targetEntity = PhoneNumber.class)
List phoneNumberList;
public Person() {
// empty
}
public Person(int persId, String firstName, String surname, String emailAddress) {
this.persId = persId;
this.firstName = firstName;
this.surname = surname;
this.emailAddress = emailAddress;
}
public List getPhoneNumberList() {
return phoneNumberList;
}
public void setPhoneNumberList(List<PhoneNumber> phoneNumberList) {
this.phoneNumberList= phoneNumberList;
}
public int getPersId() {
return persId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#Override
public String toString() {
return "Person [persId=" + persId + ", firstName=" + firstName + ", surname=" + surname + ", emailAddress=" + emailAddress + "]";
}
}
Here is my persistance.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="jpaTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/test" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.password" value="" />
<property name="schemaUpdate" value="true" />
</properties>
</persistence-unit>
</persistence>
and the jpaTest class, supposed to make the connection
package ~path.examples.service;
import ~path.examples.testjpa.domain.Person;
import javax.persistence.*;
/**
* Created by Me on 2015-04-22.
*/
public class JpaTest {
public static void main(String args[]) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpaTest");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
Person person = new Person();
person.setFirstName("Charles");
person.setSurname("Dickens");
em.persist(person);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}
}
When I try to run it, I get the following:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1371)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
at eu.rivetgroup.examples.service.JpaTest.main(JpaTest.java:16)
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:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1263)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:57)
... 6 more
Caused by: java.sql.SQLException: No suitable driver found for jdbc:h2:~/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:276)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 11 more
My guess is, that I'm missing something obvious, as I am an inexperienced user.
However, I looked at all the places that I could find, and so far no answer has seemed to help me
thanks for your help!
I can't figure out what the problem is, please help. I've searched a lot, but didn't find any useful advice. Maybe you can help me. Thanks a lot.
There are two classes using eclipselink as jpa provider:
#Entity
#Table(name = "USER")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String login;
private Long groupId;
private String email;
#ManyToMany(mappedBy = "users")
private List polls;
#OneToMany(mappedBy = "user")
private List votes;
public List getVotes() {
return votes;
}
public void setVotes(List votes) {
this.votes = votes;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List getPolls() {
return polls;
}
public void setPolls(List polls) {
this.polls = polls;
}
}
and
#Entity
#Table(name = "VOTE")
public class Vote {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long vid;
private String comment;
#ManyToOne
private User user;
#ManyToOne
private Option option;
public Vote() {
}
public Long getVid() {
return vid;
}
public void setVid(Long vid) {
this.vid = vid;
}
#Column(name = "comment")
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Option getOption() {
return option;
}
public void setOption(Option option) {
this.option = option;
}
}
When I'm trying to compile this, I receive error:
Exception [EclipseLink-7214] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The target entity of the relationship attribute [votes] on the class [class logic.User] cannot be determined. When not using generics, ensure the target entity is defined on the relationship mapping.
Here is my persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<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="pollsPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>logic.Option</class>
<class>logic.Poll</class>
<class>logic.User</class>
<class>logic.Vote</class>
<class>logic.Greeting</class>
<properties>
<property name="eclipselink.jdbc.password" value="" />
<property name="eclipselink.jdbc.user" value="" />
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="eclipselink.jdbc.url"
value="jdbc:mysql://localhost:3306/core_polls" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence>
As stated in the Javadoc
If the collection is defined using generics to specify the element
type, the associated target entity type need not be specified;
otherwise the target entity class must be specified.
So, you can do either
#OneToMany(mappedBy = "user")
private List<Vote> votes;
or
#OneToMany(targetEntity=logic.Vote.class, mappedBy = "user")
private List votes;
But I would prefer the first.
Greetings my folks I'm using JPA 2.0 and so far I'm not really getting any kind of error from anywhwere in the project, however the data is not persiting into the database at all, this is my persistence.xml (just the pu) file as it looks right now:
<persistence-unit name="auto-core-pu" transaction-type="RESOURCE_LOCAL">
<description>Auto Core Persistence Unit</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.auto.core.model.Cars</class>
<class>com.auto.core.model.Client</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/auto_core"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
This is my EntityManagerClient.class
package com.auto.core.persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.auto.core.model.Cars;
public class EntityManagerClient {
public static void main(String[] args){
EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
EntityTransaction t = em.getTransaction();
t.begin();
Cars cr = new Cars();
cr.setBrand("Toyota");
cr.setModel("Camry");
cr.setEngine("V6");
cr.setDoors(5);
cr.setType("Jeepeta");
cr.setYear(123);
cr.setDescription("Auto usado del año 123 D.C.");
t.commit();
}
public static void getData(){
EntityManager em = Persistence.createEntityManagerFactory("auto-core-pu").createEntityManager();
EntityTransaction g = em.getTransaction();
g.begin();
Cars cr = em.createNamedQuery("Cars.FindbyId", Cars.class).setParameter("id", 1L).getSingleResult();
System.out.println(cr.getBrand());
}
}
and lass an example of how I did the annotations in other classes:
#Entity
#Table(schema="auto_core" , name="client")
public class Client {
#Id
#GeneratedValue
long id;
#Column(name="name")
String name;
#Column(name="lastname")
String lastname;
#Column(name="email")
String email;
#Column(name="address")
String address;
#Column(name="address2")
String address2;
#Column(name="zip")
String zip;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Again, I'm not getting any kind of error, is just that I can't persist data, or query data that I put manually into the database, that's all.
It's because you're getting the EntityManager, opening the transaction, and creating the object but you don't persist it. You have to invoke:
em.persist(cr);
before
t.commit();
Until you persist it, it's just a POJO in memory.