预期结果:如何像我共享一个屏幕快照链接那样从大学角色打印数据
屏幕截图:http://imgur.com/H3wolaB
项目结构:http://imgur.com/IRxGJeq
进行简单登录并显示用户类型数据
我在eclipse juno中创建了一个休眠项目
我正在使用2节课
1)College_UserLogin
2)College_Role
我试图使用两个类中提到的通用键“ RoleID”从第二类获取用户类型(例如学生)的数据。
但是我遇到了这种例外情况,并且被卡住了,
堆栈跟踪
初始SessionFactory创建
failed.org.hibernate.HibernateException:缺少列:
CERPDevNew.dbo.College_Role中的college_UserLogin
注意:College_UserLogin是表而不是列,但是编译器将其理解为列,这是我的问题
@Entity
@Table(name = "College_Role")
//@Inheritance(strategy = javax.persistence.InheritanceType.TABLE_PER_CLASS)
//@DiscriminatorValue("College_Role")
//@PrimaryKeyJoinColumn(name="RoleID")
public class College_Role implements Serializable {
private static final long serialVersionUID = 9182318500460817975L;
@Id
//@GeneratedValue(strategy=GenerationType.AUTO)
//@OneToOne(mappedBy="collegeRole")
//@PrimaryKeyJoinColumn(name="roleID")
//@JoinColumn(name="roleID",referencedColumnName="roleID", unique= true, nullable=true, updatable = false, insertable = false)
@JoinColumn(name="roleID",unique= true, nullable=false, insertable=false, updatable=false)
public College_UserLogin college_UserLogin;
public College_UserLogin getCollege_UserLogin() {
return college_UserLogin;
}
public void setCollege_UserLogin(College_UserLogin college_UserLogin) {
this.college_UserLogin = college_UserLogin;
}
@Column(name="RoleID")
private int roleID;
://body
**College_UserLogin.java**
@Entity
@Table(name = "College_UserLogin")
//@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
//@DiscriminatorColumn(name = "College_UserLogin", discriminatorType = DiscriminatorType.STRING)
public class College_UserLogin implements Serializable {
private static final long serialVersionUID = 6304741905092879739L;
@Id
//@GeneratedValue(strategy=GenerationType.IDENTITY)
//@AttributeOverride(name="roleID", column=@Column(name="roleID"))
// @OneToOne(cascade=CascadeType.ALL, mappedBy="College_UserLogin")
// @PrimaryKeyJoinColumn
//@JoinColumn(name="roleID",referencedColumnName="role_ID", unique= true, nullable=true, updatable = false, insertable = false)
private College_Role college_Role;
public College_Role getCollege_Role() {
return college_Role;
}
public void setCollege_Role(College_Role college_Role) {
this.college_Role = college_Role;
}
public College_UserLogin(){
}
//body
更新的HibernateUtil类
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static Configuration configuration;
**added entity manager factory and entity manager**
static EntityManagerFactory emf = Persistence.createEntityManagerFactory("Rest-WS");
static EntityManager em = emf.createEntityManager();
/* All SQL, DML entities must be registered */
public static void registerBeans() {
configuration.addAnnotatedClass(College_UserLogin.class);
configuration.addAnnotatedClass(College_Role.class);
}
private static final SessionFactory buildSessionFactory() {
try {
configuration = new Configuration();
configuration.configure();
registerBeans();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static void main(String args[]) throws Exception {
//these line i have added// em.getTransaction().begin();
College_UserLogin college_UserLogin = new College_UserLogin();
em.persist(college_UserLogin);
College_Role college_Role = new College_Role();
// college_Role.setName("dept name");
college_UserLogin.setCollege_Role(college_Role);
em.flush();
//up to here these lines i have added//
HibernateUtil.getSessionFactory();
//Changes i made
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
Session session=sessionFactory.openSession();
// Query query=session.createQuery("select * from College_UserLogin where UserID='ATME.admin'");
@SuppressWarnings("unchecked")
List<College_UserLogin> list= (List<College_UserLogin> )session.createQuery("from College_UserLogin where userid='atme.admin' ").list();
Iterator<College_UserLogin> itr=list.iterator();
// while(itr.hasNext()){
//College_UserLogin clg_login = null;
College_UserLogin clg_login=itr.next();
System.out.println(clg_login.getUserID() + itr.next() +" "+ clg_login.getEmailID() + itr.next());
College_Role clg_role =clg_login.getCollege_Role(); ;
System.out.println(" "+
clg_role.getRoleDescription() + itr.next() +" "+clg_role.getSuperiorHeirarchy() + itr.next());
//these lines i have added//
System.out.println("success");
em.getTransaction().commit();
em.close();
emf.close();
}
}
完整的堆栈跟踪
Sep 30, 2015 12:28:03 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Sep 30, 2015 12:28:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.0.Final}
Sep 30, 2015 12:28:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 30, 2015 12:28:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 30, 2015 12:28:03 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Sep 30, 2015 12:28:03 PM org.hibernate.cfg.Configuration
getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Sep 30, 2015 12:28:04 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Sep 30, 2015 12:28:04 PM
org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderI
mpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Sep 30, 2015 12:28:04 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 100
Sep 30, 2015 12:28:04 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
Sep 30, 2015 12:28:04 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at
URL [jdbc:sqlserver://172.18.1.30;Database=CERPDevNew;]
Sep 30, 2015 12:28:04 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=Sa, password=****, autocommit=true}
Sep 30, 2015 12:28:04 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServer2008Dialect
Sep 30, 2015 12:28:04 PM
org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Sep 30, 2015 12:28:04 PM
org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Sep 30, 2015 12:28:04 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.1.2.Final
Sep 30, 2015 12:28:04 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Sep 30, 2015 12:28:04 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Sep 30, 2015 12:28:04 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: CERPDevNew.dbo.College_Role
Sep 30, 2015 12:28:04 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [stafftype, isactive, superiorheirarchy, roleid, roledescription]
Initial SessionFactory creation failed.org.hibernate.HibernateException: Missing column: college_UserLogin in CERPDevNew.dbo.College_Role
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.orcta.dao.HibernateUtil.buildSessionFactory(HibernateUtil.java:40)
at com.orcta.dao.HibernateUtil.<clinit>(HibernateUtil.java:17)
Caused by: org.hibernate.HibernateException: Missing column: college_UserLogin in CERPDevNew.dbo.College_Role
at org.hibernate.mapping.Table.validateColumns(Table.java:275)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1268)
at
org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:453)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
at com.orcta.dao.HibernateUtil.buildSessionFactory(HibernateUtil.java:35)
... 1 more
提前致谢。这将对高级Java初学者有很大的帮助
最佳答案
@PiyushSoni您不得对@OneToOne和@JoinColumn批注发表评论! Hibernate的原因认为它只是一列(必须由外键关联)。您必须在College_UserLogin类中添加@OneToOne和@JoinColumn批注,并在College_Role类中添加带有“ mappedBy”的@OneToOne。使用此批注,您将在College_UserLogin中将一个外键字段链接到College_Role。
如果要在College_UserLogin和College_Role中具有外键,则必须在College_UserLogin类中添加@OneToOne和@JoinColumn注释,并在College_Role类中添加@OneToOne和@JoinColumn注释。
我为您准备了一个例子。它使用User class(您的College_UserLogin的类似物)和UserAddress class(您的College_Role的类似物)。请参阅方法User.getAddress()和UserAddress.getUser()的注释。