Я хочу создать веб-приложение и впервые использовать JPA для слоя модели в MVC. Но у меня проблемы.
Программа показывает мне эту ошибку:
Nov 11, 2018 10:56:49 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" java.lang.ExceptionInInitializerError
at model.bl.PersonManager.main(PersonManager.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: MyConnection] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:930)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:72)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at util.JPAProvider.<clinit>(JPAProvider.java:13)
... 6 more
Caused by: org.hibernate.MappingException: Unable to find column with logical name: UID in org.hibernate.mapping.Table(USERS) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:552)
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:257)
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1331)
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:791)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:719)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:668)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1593)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1350)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 11 more
Класс человека:
package model.entity;
import model.bl.PersonManager;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
//mapping class to table
@Entity (name = "person")
@Table(name = "USERS")
@EntityListeners(value = PersonManager.class)
public class Person implements Serializable
{
@Id // create id and fill auto by sequence in database
@Column(name="UID" ,columnDefinition = "NUMBER" )
@SequenceGenerator(name = "mySeq" , sequenceName = "DB_MYSEQ")
@GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq")
private long uId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
private List<Pictures> picturesList;
@Basic
@Column (name = "USERNAME" , columnDefinition = "NVARCHAR2(30)" , nullable = false , unique = true)
private String username ;
@Basic
@Column (name = "USER_PASSWORD" , columnDefinition = "NVARCHAR2(32)" , nullable = false , unique = true)
private String password ;
@Basic
@Column (name = "EMAIL" , columnDefinition = "NVARCHAR2(40)" , nullable = false)
private String email;
@Basic
@Column (name = "SEX" , columnDefinition = "NVARCHAR2(20)")
private String sex ;
//--------------------------------------------------------
public Person() { }
public Person(String username, String password, String email, String sex, String userPic) {
this.username = username;
this.password = password;
this.email = email;
this.sex = sex;
this.userPic = userPic;
}
public Person(String username, String password, String email ,String sex, String userPic,List<Pictures> picturesList ) {
this.picturesList = picturesList;
this.sex = sex;
this.userPic = userPic;
this.email = email;
this.password = password;
this.username = username;
}
//--------------------------------------------------------
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setUserPic(String userPic) {
this.userPic = userPic;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setuId(long uId) {this.uId = uId;}
//--------------------------------------------------------
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUserPic() {
return userPic;
}
public String getEmail() {
return email;
}
public String getSex() {
return sex;
}
public long getuId() {return uId;}
}
}
Класс фотографий:
package model.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity(name = "picture")
@Table(name = "PICTURE")
public class Pictures implements Serializable
{
@Id // create id and fill auto by sequence in database
@Column(name="PID" ,columnDefinition = "NUMBER" )
@SequenceGenerator(name = "mySeq2" , sequenceName = "DB_MYSEQ2")
@GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq2")
private long pId;
@Basic
@Column (name = "PICADRESS" , columnDefinition = "NVARCHAR2(50)" , nullable = false)
private String picAdress ;
@Basic
@Column (name = "CAPTION" , columnDefinition = "LONG")
private String caption;
@Basic // user picture for profile
@Column (name = "LIKES" , columnDefinition = "NUMBER")
private int likes;
//--------------------------------------------------------
public Pictures(){}
public Pictures( String picAdress, String caption, int likes) {
this.picAdress = picAdress;
this.caption = caption;
this.likes = likes;
}
//--------------------------------------------------------
public void setPid(long pid) {
this.pId = pid;
}
public void setLikes(int likes) {
this.likes = likes;
}
public void setPicAdress(String picAdress) {
this.picAdress = picAdress;
}
public void setCaption(String caption) {
this.caption = caption;
}
//--------------------------------------------------------
public int getLikes() {
return likes;
}
public String getCaption() {
return caption;
}
public String getPicAdress() {
return picAdress;
}
public long getPid() {
return pId;
}
}
Мой JPA-провайдер:
public class JPAProvider {
private static final EntityManagerFactory entityManagerFactory;//instate of session for connect to database
static{
entityManagerFactory = Persistence.createEntityManagerFactory("MyConnection");
}
public static EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}
Класс PersonManager:
public class PersonManager {
public static void main(String[] args) {
EntityManager entityManager = JPAProvider.getEntityManagerFactory().createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Person person = new Person("midas" , "midas123" , "aaaaa@gmail.com", "female" ,"female-user.png" );
Pictures pictures = new Pictures("aaa" , "akflkkglhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" ,2);
Pictures pictures2 = new Pictures("nnbnbn" , "affddAlllllllllllllllllllllllllllllllllllll" ,5);
List<Pictures> picturesList =new ArrayList<Pictures>();
picturesList.add(pictures);
picturesList.add(pictures2);
person.setPicturesList(picturesList);
entityManager.persist(person);
entityTransaction.commit();
entityManager.close();
}
}
и persistence.xml:
<persistence-unit name="MyConnection" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.username" value="midas"/>
<property name="hibernate.connection.password" value="midas123"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"></property>
<property name="hibernate.globally_quoted_identifiers" value="true"/>
</properties>
</persistence-unit>
Я использовал следующие библиотеки:
1) hibernate-enverc-4.2.0.final * * 1 021
2) спящий режим-JPA-2.0-API-1.0.1-final.jar * * 1 023
3) библиотека котов
моя версия JDK = 1.8.0-172
my IDE = IntellyJ Idea
Я использую Oracle 11g.
Я пытался решить проблему, решая похожие вопросы, но не смог.
например, я проверил следующие темы, которые были более похожи на мою проблему:
[ Ошибка создания компонента с именем entityManagerFactory, определенным в ресурсе пути к классу: сбой вызова метода init
[ Получение исключения в потоке "main" java.lang.ExceptionInInitializerError Exception
Дополнительное объяснение: Таблицы в базе данных пока не созданы.