映射异常未知实体



出于某种原因,当我使用 save 方法时,我得到一个映射异常。我将映射标记放在Hibernate.cfg.xml文件中,并将相应的类标记为实体。

理论上,它应该在驱动程序(用于测试 ORM(中调用后向我的数据库添加新用户

文件系统和异常位置

[休眠.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>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@atomicity.ciwxju2fmzjg.us-east-2.rds.amazonaws.com:1521:ORCL</property>
<property name="hibernate.connection.username">Master</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping class="domain.Users" />
<mapping class="domain.ProfilePics" />
<mapping class="domain.Topics" />
<mapping class="domain.Posts" />
</session-factory>

[用户.java]

package domain;
import javax.persistence.*;
@NamedQueries({ @NamedQuery(name = "getAllUsers", query = "FROM Users"),
@NamedQuery(name = "getUsersByUsername", query = "FROM Users user WHERE user.username = :var") })
@Entity
@Table(name = "A_USERS")
public class Users {
public Users() {
super();
}
public Users(String username, String email, String password, String firstName, String lastName, boolean blocked) {
super();
this.username = username;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.blocked = blocked;
}
@Id
@Column(name = "U_USERNAME")
private String username;
@Column(name = "U_EMAIL")
private String email;
@Column(name = "U_PASSWORD")
private String password;
@Column(name = "U_FIRSTNAME")
private String firstName;
@Column(name = "U_LASTNAME")
private String lastName;
@Column(name = "BLOCKED")
private boolean blocked;
public String getUsername() {
return username;
}
public Users setUsername(String username) {
this.username = username;
return this;
}
public String getFirstName() {
return firstName;
}
public Users setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public Users setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public boolean isBlocked() {
return blocked;
}
public Users setBlocked(boolean blocked) {
this.blocked = blocked;
return this;
}
public String getPassword() {
return password;
}
public Users setPassword(String password) {
this.password = password;
return this;
}
public String getEmail() {
return email;
}
public Users setEmail(String email) {
this.email = email;
return this;
}
}

[用户DAOImpl.java]

package dao;
import static org.junit.Assert.*;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import customExceptions.*;
import util.Debug;
import util.HibernateUtil;
import domain.Users;
@Transactional
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionfactory) {
this.sessionFactory = sessionfactory;
}
@Test
public void testPush() {
try {
push(new Users("username6", "email@gmail.com", "password", "firstName", "lastName", false));
} catch (UserNameTakenException e) {
e.printStackTrace();
fail();
} catch (InvalidNameException e) {
e.printStackTrace();
fail();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
fail();
}
}
/**
* Adds a new user to the database
* 
* @param newUser
*            The user to be added
* @throws UserNameTakenException
*             In the case a username is taken
* @throws InvalidNameException
*             If a field is left blank, but front end should prevent that
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void push(Users newUser) throws UserNameTakenException, InvalidNameException {
// For debugging purposes:
Debug.printMessage(this.getClass(), "push()", "invoked");
// Check if there are any empty Strings
if (newUser.getUsername().isEmpty() || newUser.getPassword().isEmpty() || newUser.getFirstName().isEmpty()
|| newUser.getLastName().isEmpty()) {
throw new InvalidNameException("There is an empty String");
}
// Get the session
Session sess = sessionFactory.getCurrentSession();
// Check to see if the username is taken
Users users = getUserByName(newUser.getUsername());
// If the list is not empty, a user with the name was found
if (users != null) {
sess.close();
throw new UserNameTakenException("The username was found in the database");
} else {
// Otherwise, add the new user
// Debug
Debug.printMessage(this.getClass(), "push()", "username available.");
Debug.printErrorMessage(this.getClass(), "push()", "saving " + newUser.getUsername());
sess.save(newUser);
sess.close();
}
}
/**
* Updates the User's password in the database
* 
* @param user
*            The user to change
* @param newVal
*            The new password
*/
@Override
public void updatePassword(Users user, String newVal) {
Debug.printMessage(this.getClass(), "updatePassword()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setPassword(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's first name in the database
* 
* @param user
*            The user to change
* @param newVal
*            The new first name
*/
@Override
public void updateFirstName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateFirstName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setFirstName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's last name in the database
* 
* @param user
*            The user to change
* @param newVal
*            The new last name
*/
@Override
public void updateLastName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateLastName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setLastName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Returns the user with the given username
* 
* @param username
*            The username to find
*/
@Override
public Users getUserByName(String username) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getUserByName()", "invoked");
Session sess = HibernateUtil.getSession();
Users user = (Users) sess.get(Users.class, username);
sess.close();
return user;
}
/**
* Returns a list of all users from A_USERS
*/
@Override
public List<Users> getAllUsers() {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getAllUsers()", "invoked");
Session sess = HibernateUtil.getSession();
Query query = sess.getNamedQuery("getAllUsers");
List<Users> users = query.list();
sess.close();
return users;
}
}

[驱动程序.java]

package testDrivers;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import customExceptions.InvalidNameException;
import customExceptions.UserNameTakenException;
import dao.UsersDAO;
import domain.Users;

public class Driver {
public static void main(String args[]) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
UsersDAO dao = (UsersDAO) ac.getBean("usersDAO");
try {
dao.push(new Users("username6", "email@gmail.com", "password", "firstName", "lastName", false));
} catch (UserNameTakenException e) {
System.out.println("Username taken");
e.printStackTrace();
} catch (InvalidNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((AbstractApplicationContext) ac).close();
}
}

堆栈跟踪

Exception in thread "main" org.hibernate.MappingException: Unknown entity: domain.Users
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 dao.UsersDAOImpl.push(UsersDAOImpl.java:78)
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:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy14.push(Unknown Source)
at testDrivers.Driver.main(Driver.java:18)

您可以忽略 testPush 方法,因为它在导致其他错误后未被使用。

任何帮助不胜感激

尝试以另一种方式获得sessionFactory,如下所示:

final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}

最新更新