预期结果:如何从大学角色打印数据,就像我分享了一个屏幕截图链接
截屏:http://imgur.com/H3wolaB 项目结构:http://imgur.com/IRxGJeq
处理简单登录并显示用户类型数据 我在eclipse juno中创建了一个hibernate项目 我正在使用2个班级 1)College_UserLogin 2)College_Role
我正在尝试从第二课获取usertype(比如学生)使用共同密钥' RoleID'在两个班级中提到。 但我得到了这个例外,我被困住了,
堆栈跟踪
创建初始SessionFactory failed.org.hibernate.HibernateException:缺少列: college_UserLogin in CERPDevNew.dbo.College_Role
注意: 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初学者来说,这将是一个很好的帮助
答案 0 :(得分:1)
@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 calss)。请参阅有关方法User.getAddress()和UserAddress.getUser()的注释。
答案 1 :(得分:0)
你不应该使用@JoinColumn注释 @OneToMany(或@OneToOne)。
P.S。您的会话工厂初始化将无法正常用于Hibernate 5.尝试使用fluent-hibernate进行工厂初始化并执行简单请求。一个使用Hibernate和MySQL的简单示例,您可以找到here。随便在GitHub上向我询问有关此库的任何信息。