How to ignore columns class fields in Hibernate Missing column: in databasetable


Discount: https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring32coupon

Caused by: org.hibernate.HibernateException: Missing column: test in databasetable
at org.hibernate.mapping.Table.validateColumns(Table.java:276)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1313)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1842)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)
… 61 more

Solution is adding @Transient to column like as below;

@Transient
private String test;

Advertisements

ERROR LazyInitializationException:42 – failed to lazily initialize a collection of role no session or session was closed org.hibernate.LazyInitializationException


Discount: https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring32coupon

19 aug 2015 10:03:24,448 ERROR LazyInitializationException:42 – failed to lazily initialize a collection of role: class, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: class, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)

Solution on JUnit tests

@Test
@Transactional

And @Entity level use fetch = FetchType.EAGER

@OneToMany(mappedBy = "groups", fetch = FetchType.EAGER)

org.hibernate.JDBCException: Error during import script execution


Discount: https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring32coupon

Hibernate by default tries to import SQLs under (classpath);
resources folder named as import.sql;

So you should edit the content of this SQL file.

17 aug 2015 17:05:27,027 INFO SchemaExport:348 – Executing import script: /import.sql
17 aug 2015 17:05:27,030 ERROR SchemaExport:287 – schema export unsuccessful
org.hibernate.JDBCException: Error during import script execution at line 1
at org.hibernate.tool.hbm2ddl.SchemaExport.importScript(SchemaExport.java:370)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:276)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:219)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:372)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1842)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)

Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25
https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

Redemption Code: edulearnspring25

Hi,

I am Tuna Tore and the owner of this technical blog;

I created an online course for learning the details and usages of Spring Framework in commercial environments.

If you would like to learn the latest version of Spring Framework with step by step examples/codes and pass Core Spring Framework Certification 4.x then you can attend this udemy course through the following link;

Spring Framework 4.x Course and Core Spring Certification

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

If you attend this course through this link, I will provide more than %50 discount coupon.
Actual course price is 59 euros and with this link you will be able to learn and code Spring Framework Applications by only paying
25 euros (instead of 59 euros)

Here you can find the contents of udemy Spring Framework Course;

  • Spring Container, Dependency, and IOC (Inversion of Control)
  • Spring Aspect Oriented Programming
  • Spring JDBC, Transactions, and ORM (Hibernate)
  • Spring MVC
  • Spring Security
  • Spring Messaging (JMS)
  • REST
  • Unit Testing with JUnit for Spring Applications
  • Library Management with Maven using STS (Spring Tool Suite)

After attending the course, if you have any questions, I will be ready to support you.

Regards,

Hibernate validator example



package nl.kameroom.user;

import java.util.Date;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

public class BasicRegister {

	private int idAuthority;

	@Email (message = "2.email.format")
        @Length(min=1, max = 100, message="3.email.length") 
	private String email;

        @Length(min=1, max = 100, message="5.pass.length")  
	private String password;

        @Length(min=1, max = 100, message="7.firstname.length") 
	private String firstname;

        @Length(min=1, max = 100, message="9.lastname.length") 
	private String lastname;

        @Length(min= 1, max = 1, message="11.gender.length") 
	private String gender;

	public int getIdAuthority() {
		return idAuthority;
	}
	public void setIdAuthority(int idAuthority) {
		this.idAuthority = idAuthority;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

        public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

How to create a Hibernate Web Application (Simple example)


First of all, create a Hibernate.cfg.xml file and put it into WEB-INF/classes folder inside WAR file.
I am using derby database (bundled in Java)in this project.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;
<hibernate-configuration>
  <session-factory>
    <property name=”hibernate.dialect”>org.hibernate.dialect.DerbyDialect</property>
    <property name=”hibernate.connection.driver_class”>org.apache.derby.jdbc.ClientDriver</property>
    <property name=”hibernate.connection.url”>jdbc:derby://localhost:1527/sample</property>
    <property name=”hibernate.connection.username”>app</property>
    <property name=”hibernate.connection.password”>app</property>
    <property name=”current_session_context_class”>thread</property>
     <mapping/>
  </session-factory>
</hibernate-configuration>

Create a Customer.java file

package com.tunatore.hibernateexample;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author tunatore
 */

@Entity
@Table(name = “CUSTOMER”) //reference for the table inside Database
public class Customer implements Serializable{

    @Id //Colum CUSTOMER_ID inside database will be mapped to customer_ID
    @Column(name = “CUSTOMER_ID”)
    private int customer_ID;
 //Colum NAME inside database will be mapped to customer_ID
    @Column(name = “NAME”)
    private String name;
 //Colum CITY inside database will be mapped to city
    @Column(name = “CITY”)
    private String city;
//Colum STATE inside database will be mapped to state
    @Column(name = “STATE”)
    private String state;
/**

     * @return the customer_ID
     */
    public int getCustomer_ID() {
        return customer_ID;
    }
/**
     * @param customer_ID the customer_ID to set
     */
    public void setCustomer_ID(int customer_ID) {
        this.customer_ID = customer_ID;
    }
/**

     * @return the name
     */
    public String getName() {
        return name;
    }
/**

     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
/**

     * @return the city
     */
    public String getCity() {
        return city;
    }
/**

     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }
/**

     * @return the state
     */
    public String getState() {
        return state;
    }
/**

     * @param state the state to set
     */
    public void setState(String state) {
        this.state = state;
    }

}

Create a HibernateManager.java file for getting SessionFactory object from Hibernate ORM.

package com.tunatore.hibernateexample;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateManager // Hibernate utility class
{
  private static final SessionFactory sessionFactory;

  static {    //create sessionFactory only once    
    try {
      // creating the SessionFactory from hibernate.cfg.xml            
      sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    } catch (Throwable ex) {
           System.err.println(“SessionFactory initial creation error.”+ ex);
      throw new ExceptionInInitializerError(ex);
    }
  }
  public static SessionFactory getSessionFactory() {
     return sessionFactory;
  }

}

Create a business operations class HibernateExample.java
package com.tunatore.hibernateexample;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author tunatore
 */
public class HibernateExample {

    public static Customer[] getCustomersInState(String stateName) {

    //create SessionFactory object for opening Session
SessionFactory sessionFactory  = HibernateManager.getSessionFactory();

    Session session = sessionFactory.getCurrentSession();
//Criteria requires a transaction opened
    session.beginTransaction();
    //create Criteria for Customer class
Criteria criteria = session.createCriteria(Customer.class);

//add a Restriction which will be used for equality –> state = ‘MI’
criteria.add(Restrictions.eq(“state”, stateName));
//add an order for using customer_ID column
criteria.addOrder(Order.asc(“customer_ID”));
//return the resultset as a List
List<Customer> customers = criteria.list();

//convert List to Array
    return customers.toArray(new Customer[customers.size()]);

    }
}

And last, create a index.jsp file for testing bussiness method –>getCustomersInState()

<%–
    Document   : index
    Created on : 14.June.2011, 20:29:36
    Author     : tunatore
–%>

<%@page import=”com.tunatore.hibernateexample.HibernateManager”%>
<%@page import=”org.hibernate.SessionFactory”%>
<%@page import=”com.tunatore.hibernateexample.Customer”%>
<%@page import=”com.tunatore.hibernateexample.HibernateExample”%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>Customers in State –> MI</title>
    </head>
    <body >
        <h1>Customers</h1>
        <table width=”600px” border=”1″ bgcolor=”#FFF380″>
            <tr>
                <th width=”100px”>Customer_ID</th>
                <th width=”100px”>City</th>
                <th width=”100px”>State</th>
                <th width=”100px”>Name</th>
            </tr>
            <tr>                
            <%
                Customer[] customerArr = HibernateExample.getCustomersInState(“MI”);
                for(int i=0; i < customerArr.length; i++){
            %>
            <tr>
                <td><b><%=customerArr[i].getCustomer_ID()%></b></td>
                <td><b><%=customerArr[i].getName()%></b></td>
                <td><b><%=customerArr[i].getCity()%></b></td>
                <td><b><%=customerArr[i].getState()%></b></td>                
            </tr>
            <%
                }
                HibernateManager.getSessionFactory().getCurrentSession().disconnect();
            %>               
            </tr>
        </table>
    </body>
</html>

Output of the Application


Download Project’s source (WAR file)

Exception:org.hibernate.HibernateException: No CurrentSessionContext configured!


If you get an exception while using Hibernate;
org.hibernate.HibernateException: No CurrentSessionContext configured! org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:542) com.tunatore.hibernateexample.HibernateExample.getCustomersInState(HibernateExample.java:22) org.apache.jsp.index_jsp._jspService(index_jsp.java:73) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

Add the following line inside hibernate.cfg.xml file

<property name=”current_session_context_class”>thread</property>

like the following;

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;

<hibernate-configuration>
  <session-factory>
    <property name=”hibernate.dialect”>org.hibernate.dialect.DerbyDialect</property>
    <property name=”hibernate.connection.driver_class”>org.apache.derby.jdbc.ClientDriver</property>
    <property name=”hibernate.connection.url”>jdbc:derby://localhost:1527/sample</property>
    <property name=”hibernate.connection.username”>app</property>
    <property name=”hibernate.connection.password”>app</property>
<property name=”current_session_context_class”>thread</property>
  </session-factory>
</hibernate-configuration>