0

Expected result: how to print data from college role like i shared a screen shot link

Screen shot: https://i.sstatic.net/eSNQO.jpg project structure: https://i.sstatic.net/UkOGY.jpg

Working on simple login and show user type data where I created a hibernate project in eclipse juno I am using 2 classes 1) College_UserLogin 2) College_Role

and I am trying to get data from 2nd class for the usertype (say student) USING THE COMMON KEY 'RoleID' mentioned in both classes. but I am getting this exception and I am stuck,

Stacktrace

Initial SessionFactory creation failed.org.hibernate.HibernateException: Missing column: college_UserLogin in CERPDevNew.dbo.College_Role

NOTE: College_UserLogin is table not column but compiler is understanding it as column THIS IS MY PROBLEM

    @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

UPDATED HibernateUtil class

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();

}

    }

Complete Stack trace

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

Thanks in advance. it will be great help to a beginner in advanced java

5
  • For starters, can you format the code properly, it looks so horrible, and post the stacktrace as well, not just one line of error. Commented Sep 30, 2015 at 7:22
  • No, you did not create a JPA project. You created a HIBERNATE project. This is the Hibernate API. You have no EntityManagerFactory or EntityManager. Commented Sep 30, 2015 at 7:24
  • Sorry and thanks for the valuable answer. will add entity manager factory in hibernate util and i will update the post with stack trace i am getting. Commented Sep 30, 2015 at 7:28
  • You can configure hibernate for updating your schema in persistence.xml. <property name="hibernate.hbm2ddl.auto" value="update"/>. Use "update" only in development environment ; for production, "validate". Commented Sep 30, 2015 at 7:46
  • @Andre thank you for the reply, i already did Update before but friend suggested that i should use validate, cuz i might alter the company's database. right now 'validate' i am going with. so, to display the college_role data, should i change it to update? Commented Sep 30, 2015 at 7:52

2 Answers 2

1

@PiyushSoni You must not to comment @OneToOne and @JoinColumn annotations! Cause of Hibernate thinks that it is just a column (It must be association by a foreign key). You must add @OneToOne and @JoinColumn annotations in College_UserLogin class, and add @OneToOne with "mappedBy" in College_Role class. With this annotations you will have a foreign key field in College_UserLogin linked to College_Role.

If you want to have foreign keys in College_UserLogin and College_Role you must add @OneToOne and @JoinColumn annotations in College_UserLogin class, and add @OneToOne and @JoinColumn annotations in College_Role class.

I have prepared an example for you. It uses User class (analogue of your College_UserLogin) and UserAddress class (analogue of your College_Role calss). Please, see annotations on methods User.getAddress() and UserAddress.getUser().

Sign up to request clarification or add additional context in comments.

4 Comments

Billion thanks for such Illustrative way to explain. will follow it and notify for same. actually this was the point that i dont know how to use annotations properly. now i got it.. :)
@PiyushSoni You are welcome. And, please, please, please don't use "_" in Java class names and field names. And I will be glad if you try to play with fluent-hibernate library cause of i need feedback of using it. :)
cant help it with "_" , its defined in db as it is see below in comment i have given snapshot of db.
@PiyushSoni Please, use @Column(name="f_some_column") to refer to columns in DB. And you can use a name strategy to autonaming columns and tables. And you don't need use the class name "College_Role" because you specify a table name in @Table(name = "College_Role")
0

You shouldn't using @JoinColumn annotation without @OneToMany (or @OneToOne).

P.S. Your session factory initialization will not work properly for Hibernate 5. Try to use fluent-hibernate for factory initialization and doing simply requests. A working simply example using Hibernate and MySQL you can find here. Feel free to ask me anything about this library on GitHub.

12 Comments

sure but after commenting join column i am getting_____ Exception in thread "main" org.hibernate.exception.SQLGrammarException: Invalid column name 'college_Role'
college_Role is name in DB or field in class. You should write field name if not using HQL
@levvy that 2 classes i am using is table in db, i generated .java formats for that. :)
@Levvy My friend, this guy uses "college_Role" for a Java class field name. For a field name, Carl!
There is no db table explained so I though he wrote bad table. My bad
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.