Someone to knows where can be the problem -
Could not find any META-INF/persistence.xml file in the classpath
I use IntelliJ and h2 database connection with Hibernate
There are my classes:
persistence:
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress DeprecatedClassUsageInspection -->
<persistence 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"
version="2.0">
<persistence-unit name="StudentPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>model.StudentInfo</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/JPA_App" />
<property name="hibernate.connection.user" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>
Entity class:
package model;
import javax.persistence.*;
#Entity
#Table(name = "Student")
public class StudentInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name", length = 30, nullable = false)
private String name;
#Column(name = "lastname", length = 30, nullable = false)
private String lastname;
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;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
and Main class
package model;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class AddStudent {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
StudentInfo student = new StudentInfo();
student.setId(0);
student.setName("John");
student.setLastname("Doe");
em.persist(student);
em.getTransaction().commit();
em.close();
emf.close();
}
}
In eclipse this simple source works but in IntelliJ I received this exception.
I would be grateful for any ideas to resolve this error.
Best regards,
D. Balamjiev
Just move your META-INF folder at the root of one of build paths of your IDE.
For example, move META-INF folder to the web folder and it should be available at the runtime.
By using a build tool such as Maven or Gradle, you would not have these kinds of problem any longer since the layout is standard and therefore the same whatever the IDE you are using.
For example, in your case, it would be both for Eclipse and IntelliJ : src/main/resources/META-INF
Related
I have org.postgresql.util.PSQLException: ERROR: relation "roles" does not exist, and I don't know why.
Entity class
package com.example.SpringBootTest1.model;
import lombok.*;
import javax.persistence.*;
#ToString
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "roles")
public class Role
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Setter
#Getter
private int id;
#Setter
#Getter
#Column(name = "name")
private String name;
}
main()
public static void main(String[] args)
{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("role_pu");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Role role1 = new Role();
role1.setName("role111");
entityManager.persist(role1);
entityManager.getTransaction().commit();
entityManagerFactory.close();
entityManager.close();
}
resources/META-INF/persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="role_pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.SpringBootTest1.model.Role</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="123"/>
<property name="dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hdm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
In pom.xml I have
hibernate-core
postgresql
lombok
So why I have such error and why is that? I have read this question and it doesn't help me.
In modern Hibernate versions, the property hdm2ddl.auto should be hibernate.hbm2ddl.auto or javax.persistence.schema-generation.database.action.
https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
I hava a model, and i need to validate model with eclipselink jpa
and i add anotation #NotEmpty validate name if empty, but when i save/persist model, validate not work
#Entity
public class Role {
#Id
private String id;
#NotEmpty
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
my jpa configuration xml like this
<?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="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>app.test.Model.Role</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
The JPA API (which EclipseLink implements) is nothing to do with the Bean Validation API.
To utilise the Bean Validation API you need the Bean Validation API jar (javax.validation), together with an implementation of that API (Apache BVAL, Hibernate Validator, etc) in your CLASSPATH.
The only thing JPA provides is to auto-enable validation as per this link, but the default is "auto" so nothing required really for that
I have a simple JPA example and I'm trying to write an entity to an H2 database.
Here is the error I am getting:
org.h2.jdbc.JdbcSQLException: Parameter "#2" is not set; SQL statement:
insert into MyEntity (name, id) values (?, ?)`
Here is my code:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("thePersistenceUnit");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
MyEntity entity = new MyEntity();
entity.setName("heyyy");
manager.persist(entity);
manager.getTransaction().commit();
My entity:
#Entity
public class MyEntity {
private String name;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public MyEntity() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
my persistence unit
<persistence-unit name="thePersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>io.tcell.MyEntity</class>
<properties>
<property name="connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.url" value="jdbc:h2:/tmp/myh2db"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
Error message:
javax.persistence.RollbackException: Error while committing the
transaction
I'm having trouble saving user data. This error has appeared, it follows the form that the project is in:
Method to save:
public void save(User u)
{
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try
{
tx.begin();
if (u.getId_User()== null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Method that receives the form data:
public String addUser(Address a, User u)
{
u.setAddress(a);
userDAO.save(u);
return "User saved successfully!";
}
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="consultoriowebPU">
<!-- Hibernate -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/bd_consultorioweb?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
User.class [model]:
#Entity
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Long Id_User;
private String email_User;
private String name_User;
private String password_User;
private int status_User;
#ManyToOne
private Address address;
//Get and set..
}
Address.class [model]:
#Entity
public class Address implements Serializable
{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Long Id_Address;
private String Country;
private String State;
private String City;
private String Neighborhood;
private String Street;
private Long Number;
private String Complement;
private String Zipcode;
//Get and set..
}
Here is the list of libraries/jar used:
http://imgur.com/a/NDmmQ
In the console, only the insert sql appears, and then the error message and no data is recorded in the database.
I assume that the Address entity that you are populating the user with, is a detached entity.
I would add the following cascade options to the User entity:
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinColumn(name = "address_id")
private Address address;
Now when the User entity is persisted / merged, then also the Address entity will be persisted / merged.
I am creating a backend application using Spring, Hibernate and JPA.
Currently the application test pass but I get a warning:
WARN: HHH000436: Entity manager factory name (JpaPersistenceUnit) is already registered.
I think the reason for this is that I defined my JpaPersistenceUnit in the persistence.xml and I also create one in my dao class. If this is the case I need to find a way to get my JpaPersistenceUnit from the persistence.xml without creating it (again). But I don't know how...
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="JpaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="groepD"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/groepd"/>
<property name="hibernate.connection.username" value="groepD"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
This is my generic dao class:
public interface GenericDao<E, ID extends Serializable> {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
public void add(E entity);
public void remove(E entity);
public void update(E entity);
public E findById(ID id);
public List<E> findAll();
}
This is the specific dao class:
public interface TripDao extends GenericDao<Trip,Integer> {
}
And this is an implementation of the dao class:
#Repository
public class TripDaoImpl implements TripDao {
protected EntityManager entityManager;
public TripDaoImpl() {
entityManager = emf.createEntityManager();
}
#Override
#Transactional
public void add(Trip entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
....
}
This is the entity:
#Entity
#Table(name = "T_TRIP")
public class Trip {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
private String name;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_ADMINS",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> admins;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_PARTICIPANT",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> invitedUsers;
#NotNull
private Boolean privateTrip;
#NotNull
private Boolean published;
#Enumerated(EnumType.STRING)
private TripType type;
#NotNull
private Integer nrDays;
#NotNull
private Integer nrHours;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "tripId")
private Set<Stop> stops;
public Trip(){
initLists();
}
private void initLists(){
this.admins = new HashSet<User>();
this.invitedUsers = new HashSet<User>();
this.stops = new HashSet<Stop>();
}
public void addStop(Stop stop) {
stops.add(stop);
}
public boolean removeStop(Stop stop) {
if (stops.size() > 1 && stops.contains(stop)) {
stops.remove(stop);
return true;
} else {
return false;
}
}
...More getters and setters...
}
If someboby could tell me how to to fix the warning that would be very helpfull.
first: (in you applicationContext.xml)
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation"
value="classpath:persistence.xml">
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="loadTimeWeaver"> <!-- 运行时植入 -->
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
next:(update you code)
remove :EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
next: you can get the class EntityManager by this
#PersistenceContext
protected EntityManager entityManager;
ps:sorry my english is so poor,
wish helpfull for you!