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.
Related
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
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.
I am trying to learn JPA
Here is my entity file.
Passenger.java
#Entity
public class Passenger implements Serializable{
public Passenger() {
super();
}
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;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
}
My persistence.xml is below.
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="JPA_POJO">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/airlines</jta-data-source>
<class>com.airline.model.Passenger</class>
</persistence-unit>
My servlet is like this.
#WebServlet(name = "addPassenger")
public class addPassenger extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Passenger p = new Passenger();
// airline p = new airline();
p.setFirstName("ABC");
p.setLastName("XYZ");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA_POJO");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
}
}
When I run this code I get the following error.
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'airline.passenger' doesn't exist
Error Code: 1146
Call: INSERT INTO PASSENGER (ID, FIRSTNAME, LASTNAME) VALUES (?, ?, ?)
As far as I can understand it is trying to connect to PASSENGER table instead of AIRLINE table.
I have assigned the data source that points to airline table. In fact I wrote a class file airline.java basically same as Passenger.java, when I used airline.java object(commented out in code) in my servlet it worked.
What am I doing wrong?
What it does seem to be totally expected, you did not provide a name to the table of your entity Passenger so it uses the name of the entity as default table name so it tries to insert into the table Passenger of the schema airline which is what is expected.
For me your problem is only that the table has not been created so far, if you want let eclipselink create your table for you, you should add the property eclipselink.ddl-generation to your file persistence.xml and set it to create-or-extend-tables as described here.
In your case it will be something like:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="JPA_POJO">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/airlines</jta-data-source>
<class>com.airline.model.Passenger</class>
<properties>
<property name="javax.persistence.jtaDataSource" value="java:/airlines"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
</properties>
</persistence-unit>
</persistence>
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.
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.