Category Archives: Java

JAVA : Collections

java.util.Collections

List Interface

A List cares about the index. All three List implementations are
ordered by index position – a position that you determine either by
setting an object at a specific index or by adding it without
specifying position, in which case the object is added to the end.

ArrayList

  • Ordered, by index
  • Unsorted
  • Fast iteration, but not fast insertion and deletion
  • Implements RandomAccess marker interface – supports
    fast (generally constant time) random access

Vector

  • Ordered, by index
  • Unsorted
  • Methods are synchronized
  • Implements RandomAccess marker interface – supports
    fast (generally constant time) random access
  • One of the the Original collections

LinkedList

  • Ordered, by index
  • Unsorted
  • Elements are doubly-linked
  • Fast insertion and deletion, not fast iteration
  • Good for implementing stacks and queues, supports adding or
    removing from beginning or end



Set Interface

A Set does not allow duplicates, it uses equals() to determine
the uniqueness

HashSet

  • Unordered
  • Unsorted
  • Uses hashCode() of the object being inserted, why?

LinkedHashSet

  • Ordered, by insertion order
  • Elements are doubly-linked
  • Use it when you care about the insertion order

TreeSet

  • Sorted, by natural order or custom implementation
  • Implements NavigableSet



Map Interface

It is about key/value pairs, keys should be unique. Relies on equals() to determine the keys’ uniqueness

HashMap

  • Unordered
  • Unsorted
  • Allows one null key and multiple null values in a collection
  • Uses hashCode(), why?
  • Faster insertion and deletion, not fast iteration

Hashtable

  • Unordered
  • Unsorted
  • Methods are synchronized
  • Does not allow null

LinkedHashMap

  • Ordered, by insertion order
  • Unsorted
  • Faster insertion, not fast insertion and deletion
  • Doubly-linked?

TreeMap

  • Sorted, by natural order or custom implementation



Queue Interface

  • Typically FIFO, but other orders are possible.
  • Priority

    • Sorted, by to-do order
    • priority-in, priority-out

    Hibernate : Mapping object associations

    Suppose there are two persistent classes called A and B. The relationship of A and
    B is called one-to-one if any instance of A is associated with only a single instance
    of B, and no more. A one-to-one association is always presented as an instance of B
    defined as a property of A, or vice versa.

    The association is called one-to-many from A to B if any instance of A can be
    associated with more than one instance of B. This relationship is established by a
    property of a collection type of B instances in class A. The one-to-many relationship
    from A to B is called many-to-one when going from B to A. In other words, when
    more than one instance of B can be associated with one instance of A.

    The final type of relationship, which is rare, is many-to-many: more than one
    instance of A can be associated with more than one instance of B. In this
    relationship, each instance of A holds a collection of B instances, and vice versa.

    one-to-one

    Two persistent classes may be associated with each other in a one-to-one
    relationship. A relationship is called one-to-one when each instance of a class
    is associated with a single instance of another class, and vice versa. If, when you
    have an instance of one class, and the other instance can be reached, then the
    one-to-one relationship is called bidirectional. On the other hand, if the objects
    cannot be reached from both sides, the relationship is unidirectional.

    • Using identical primary keys
    • 	// unidirectional
      	@Entity
      	public class Student {
      	@Id
      	private int id;
      	@OneToOne
      	@PrimaryKeyJoinColumn
      	private Phone phone;
      	//other fields and getter/setter methods
      	}
      	
      // bidirectional public class Phone { @OneToOne(mappedBy="student") // mappedBy=<propert name> private Student student; }
    • Foreign key one-to-one
    • 	public class Student {
      	@OneToOne
      	@JoinColumn(name="PHONE_ID")
      	private Phone phone;
      	}
      	

    many-to-one

    public class Student {
    	@ManyToOne
    	@JoinColumn(name="ADDRESS_ID")
    	private Address address;
    }
    

    one-to-many

    
    public class School {
    	@OneToMany(mappedBy = "school")
    	private List students = new ArrayList();
    }
    
    // ManyToOne annotation is used to map the reverse side of the one-to-many relationship public class Student { @ManyToOne @JoinColumn(name = "SCHOOL_ID") private School school; }

    many-to-many

    
    	@ManyToMany(cascade = CascadeType.ALL)
    	@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
    	public Set getCourses() { // or List
    		return courses;
    	}
    
    @Entity @Table(name = "COURSE") public class Course { @Id @GeneratedValue @Column(name = "ID") public int getId() { return id; } }

    Hibernate : Mapping inheritance hierarchy

    Hibernate has three distinct ways to map an inheritance
    relationship

    • Use one table for each concrete (nonabstract) class
    • Use one table for each class hierarchy
    • Use one table for each subclass, including interfaces and
      abstract classes

    Use one table for each concrete (nonabstract) class

    		@Entity
    		@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    		public class Student implements Serializable {
    			...
    		}
    	


    Use one table for each class hierarchy

    		@Entity
    		@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    		@DiscriminatorColumn(
    		name="PERSON_TYPE",
    		discriminatorType=STRING
    		)
    		@DiscriminatorValue("PE")
    		public class Person implements Serializable {
    		...
    		}
    		
    @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorValue("ST") public class Student extends Person{ ... }

    One table per subclass

    		@Entity
    		@Inheritance(strategy=InheritanceType.JOINED)
    		public class Person implements Serializable {
    		...
    		}
    		@Entity
    		public class Student extends Person{
    		...
    		}	
    		
    // If tables are joined by columns with different names @Entity @PrimaryKeyJoinColumn(name="STUDENT_ID") public class Student extends Person{ ... }

    JAVA: Registration Form With Spring and Hibernate

    Not working đŸ˜€

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    	<display-name>StudentReg</display-name>
    	<welcome-file-list>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
      
    	<servlet>
    		<servlet-name>dispatcher</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>/WEB-INF/config/spring-config.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    	
    	<servlet-mapping>
    		<servlet-name>dispatcher</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
      
    </web-app>
    

    spring-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="
    	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
    	<context:component-scan base-package="sam.reg" />
    	
    	<mvc:annotation-driven />
    
    	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="order" value="1"/>
    		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    		<property name="prefix">
    			<value>/WEB-INF/pages/</value>
    		</property>
    		<property name="suffix">
    			<value>.jsp</value>
    		</property>
    	</bean>
    	
    	<import resource="db-config.xml" />
    	      
    </beans>
    

    db-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:tx="http://www.springframework.org/schema/tx"
    	xmlns:aop="http://www.springframework.org/schema/aop"
    	xsi:schemaLocation="
    	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
    	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    		<property name="driverClassName">
    			<value>com.mysql.jdbc.Driver</value>
    		</property>
    		<property name="url">
    			<value>jdbc:mysql://localhost/reg</value>
    		</property>
    		<property name="username">
    			<value>root</value>
    		</property>
    		<property name="password">
    			<value></value>
    		</property>
    	</bean>
        
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    		<property name="dataSource">
    			<ref local="dataSource"/>
    		</property>
    		<property name="packagesToScan" value="sam.reg.model" />
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    				<prop key="hibernate.show_sql">false</prop>
    				<prop key="hibernate.hbm2ddl.auto">update</prop>
    			</props>
    		</property>
    	</bean>
        
    	<tx:annotation-driven/>
    	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory">
    			<ref local="sessionFactory"/>
    		</property>
    	</bean>   
    
    </beans>
    

    Course.java

    package sam.reg.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Version;
    
    @Entity
    @Table(name = "COURSE")
    public class Course {
    
    	private int id;
    	private int version;
    	private String name;
    	private String code;
    
    	@Id
    	@GeneratedValue
    	@Column(name = "ID")
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	@Column(name = "NAME", nullable = false)
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	@Column(name = "CODE", nullable = false)
    	public String getCode() {
    		return code;
    	}
    
    	public void setCode(String code) {
    		this.code = code;
    	}
    
    	@Version
    	@Column(name = "VERSION", nullable = false)
    	public int getVersion() {
    		return version;
    	}
    
    	public void setVersion(int version) {
    		this.version = version;
    	}
    
    	@Override
    	public String toString() {
    		return this.name;
    	}	
    	
    }
    

    Student.java

    package sam.reg.model;
    
    import java.util.Set;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinTable;
    import javax.persistence.ManyToMany;
    import javax.persistence.Table;
    import javax.persistence.Version;
    
    @Entity
    @Table(name = "STUDENT")
    @Inheritance(strategy = InheritanceType.JOINED)
    public class Student {
    
    	private int id;
    	private int version;
    	private String firstName;
    	private String lastName;
    	private String gender;
    	private String email;
    	private String password;
    	private Set<Course> courses;
    
    	@Id
    	@GeneratedValue
    	@Column(name = "ID")
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	@ManyToMany(cascade = CascadeType.ALL)
    	@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
    	public Set<Course> getCourses() {
    		return courses;
    	}
    
    	public void setCourses(Set<Course> courses) {
    		this.courses = courses;
    	}
    
    	@Column(name = "FIRST_NAME", nullable = false)
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public void setFirstName(String firstName) {
    		this.firstName = firstName;
    	}
    
    	@Column(name = "LAST_NAME", nullable = false)
    	public String getLastName() {
    		return lastName;
    	}
    
    	public void setLastName(String lastName) {
    		this.lastName = lastName;
    	}
    
    	@Column(name = "GENDER", nullable = false)
    	public String getGender() {
    		return gender;
    	}
    
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    
    	@Column(name = "EMAIL", nullable = false)
    	public String getEmail() {
    		return email;
    	}
    
    	public void setEmail(String email) {
    		this.email = email;
    	}
    
    	@Column(name = "PASSWORD", nullable = false)
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	@Version
    	@Column(name = "VERSION", nullable = false)
    	public int getVersion() {
    		return version;
    	}
    
    	public void setVersion(int version) {
    		this.version = version;
    	}
    
    }
    

    Undergraduate.java

    package sam.reg.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.PrimaryKeyJoinColumn;
    
    @Entity
    @PrimaryKeyJoinColumn(name="ID")
    public class Undergraduate extends Student {
    
    	private int id;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    }
    

    PostGraduate.java

    package sam.reg.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.JoinColumn;
    import javax.persistence.PrimaryKeyJoinColumn;
    
    @Entity
    @PrimaryKeyJoinColumn(name = "ID")
    public class PostGraduate extends Student {
    
    	private int id;
    	private String field;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	@Column(name = "FIELD")
    	public String getField() {
    		return field;
    	}
    
    	public void setField(String field) {
    		this.field = field;
    	}
    }
    

    CourseDao.java

    package sam.reg.dao.hibernate;
    
    import java.util.List;
    
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.stereotype.Repository;
    
    import sam.reg.model.Course;
    
    @Repository
    public class CourseDao implements sam.reg.dao.CourseDao {
    
    	private HibernateTemplate template;
    
    	@Autowired
    	public void setTemplate(SessionFactory factory) {
    		this.template = new HibernateTemplate(factory);
    	}
    
    	@Override
    	public Course save(Course course) {
    		template.saveOrUpdate(course);
    		return course;
    	}
    
    	@SuppressWarnings("unchecked")
    	@Override
    	public List<Course> retrieveAll() {
    		return template.find("from Course");
    	}
    }
    

    UndergraduateDao.java

    package sam.reg.dao.hibernate;
    
    import java.util.List;
    
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.stereotype.Repository;
    
    import sam.reg.model.Course;
    
    @Repository
    public class CourseDao implements sam.reg.dao.CourseDao {
    
    	private HibernateTemplate template;
    
    	@Autowired
    	public void setTemplate(SessionFactory factory) {
    		this.template = new HibernateTemplate(factory);
    	}
    
    	@Override
    	public Course save(Course course) {
    		template.saveOrUpdate(course);
    		return course;
    	}
    
    	@SuppressWarnings("unchecked")
    	@Override
    	public List<Course> retrieveAll() {
    		return template.find("from Course");
    	}
    }
    

    CourseService.java

    package sam.reg.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import sam.reg.dao.hibernate.CourseDao;
    import sam.reg.model.Course;
    
    @Service
    public class CourseService {
    
    	private CourseDao dao;
    
    	@Autowired
    	public void setDao(CourseDao dao) {
    		this.dao = dao;
    	}
    	
    	@Transactional
    	public Course create(Course course) {
    		return dao.save(course);
    	}
    
    	@Transactional(readOnly = true)
    	public List<Course> readAll() {
    		return dao.retrieveAll();
    	}
    }
    

    UndergraduateService.java

    package sam.reg.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import sam.reg.dao.hibernate.UndergraduateDao;
    import sam.reg.model.Undergraduate;
    
    @Service
    public class UndergraduateService {
    
    	private UndergraduateDao dao;
    
    	@Autowired
    	public void setDao(UndergraduateDao undergraduateDao) {
    		this.dao = undergraduateDao;
    	}
    
    	@Transactional
    	public Undergraduate create(Undergraduate undergraduate) {
    		return dao.save(undergraduate);
    	}
    
    	@Transactional(readOnly = true)
    	public Undergraduate read(int id) {
    		return dao.retrieve(id);
    	}
    
    	@Transactional(readOnly = true)
    	public List<Undergraduate> readAll(int id) {
    		return dao.retrieveAll();
    	}
    
    	@Transactional
    	public Undergraduate update(Undergraduate undergraduate) {
    		return dao.save(undergraduate);
    	}
    
    	@Transactional
    	public void delete(Undergraduate undergraduate) {
    		dao.delete(undergraduate);
    	}
    }
    

    CourseController.java

    package sam.reg.web;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import sam.reg.model.Course;
    import sam.reg.service.CourseService;
    
    @Controller
    @RequestMapping(value = "/course")
    public class CourseController {
    
    	private CourseService courseService;
    
    	@Autowired
    	public void setCourseService(CourseService courseService) {
    		this.courseService = courseService;
    	}
    
    	@RequestMapping(value = "/add", method = RequestMethod.GET)
    	public @ResponseBody String add() {
    		Course course = new Course();
    		course.setName("test");
    		course.setCode("455");
    		courseService.create(course);
    		return "successfuly added";
    	}
    	
    	@RequestMapping(value = "/count", method = RequestMethod.GET)
    	public @ResponseBody String readCount() {		
    		return "" + courseService.readAll().size();
    	}
    }
    

    StudentController.java

    package sam.reg.web;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.support.SessionStatus;
    
    import sam.reg.model.Course;
    import sam.reg.model.Student;
    import sam.reg.model.Undergraduate;
    import sam.reg.service.CourseService;
    import sam.reg.service.UndergraduateService;
    
    @Controller
    @RequestMapping(value = "/student")
    public class StudentController {
    
    	private CourseService courseService;
    	private UndergraduateService undergraduateService;	
    	
    	@Autowired
    	public void setUndergraduateService(UndergraduateService undergraduateService) {
    		this.undergraduateService = undergraduateService;
    	}
    
    	@Autowired
    	public void setCourseService(CourseService courseService) {
    		this.courseService = courseService;
    	}
    
    	// initialize form
    	@RequestMapping(value = "", method = RequestMethod.GET)
    	public String initForm(ModelMap model) {
    		Student student = new Undergraduate();
    		model.addAttribute("student", student);
    		return "reg-form";
    	}
    
    	// process form
    	@RequestMapping(value = "", method = RequestMethod.POST)
    	public @ResponseBody String processForm(ModelMap model,
    			@ModelAttribute("student") Undergraduate student, BindingResult result,
    			SessionStatus status) {
    		undergraduateService.create(student);
    		return student.toString();
    	}
    
    	// gender
    	@ModelAttribute("genderList")
    	public List<String> populateGenderList() {
    		List<String> list = new ArrayList<String>();
    		list.add("Male");
    		list.add("Female");
    		return list;
    	}
    
    	// degree type
    	@ModelAttribute("degreeList")
    	public List<String> populateDegreeList() {
    		List<String> list = new ArrayList<String>();
    		list.add("B.Sc.");
    		list.add("M.Sc.");
    		return list;
    	}
    
    	// courses
    	@ModelAttribute("courseList")
    	public List<Course> populateCourseList() {
    		return courseService.readAll();
    	}
    	
    	// test
    	
    	@RequestMapping(value = "/test", method = RequestMethod.GET)
    	public String test(ModelMap model) {
    		Undergraduate student = new Undergraduate();
    		student.setFirstName("fiestName");
    		student.setLastName("lastName");
    		student.setGender("gender");
    		student.setEmail("email");
    		student.setPassword("password");
    		undergraduateService.create(student);
    		return "reg-form";
    	}
    }
    

    reg-form.jsp

    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <html>
    <head>
    <title>Registration</title>
    </head>
    <body>
    	<h3>Registration Form</h3>
    
    	<form:form commandName="student" name="reg-form" method="POST">
    
    		<table>
    			<tr>
    				<td></td>
    				<td></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>First Name</td>
    				<td><form:input path="firstName" /></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>Last Name</td>
    				<td><form:input path="lastName" /></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>Gender</td>
    				<td><form:select path="gender">
    						<form:options items="${genderList}" />
    					</form:select></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>Email</td>
    				<td><form:input path="email" /></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>Password</td>
    				<td><form:input path="password" /></td>
    				<td></td>
    			</tr>
    			<tr>
    				<td>Degree type</td>
    				<td><select name="degreeType">
    						<c:forEach var="dType" items="${degreeList}">
    							<option value="${dType}">${dType}</option>
    						</c:forEach>
    				</select></td>
    				<td></td>
    			</tr>
    			<!--<tr>
    				<td>Courses</td>
    				<td><select name="crs">
    						<c:forEach var="course" items="${courseList}">
    							<option value="${course.name}">${course.name}</option>
    						</c:forEach>
    				</select></td>
    				<td></td>
    			</tr>
    			 -->
    			<tr>
    				<td>Courses</td>
    				<td><form:checkboxes items="${courseList}" path="courses" /> </td>
    				<td></td>
    			</tr>
    			<tr>
    				<td></td>
    				<td><input type="submit" value="Submit" /><input type="button"
    					value="Clear" /></td>
    				<td></td>
    			</tr>
    		</table>
    
    	</form:form>
    
    
    </body>
    </html>
    
    
    		

    Hibernate : Exception java.lang.ClassCastException: org.hibernate.mapping.JoinedSubclass cannot be cast to org.hibernate.mapping.RootClass

    you can’t have @Id in both super class and Subclass

    Solution

    Remove @Id from Subclass

    ————————–

    If tables are joined by different names use @PrimaryKeyJoinColumn(name = “IDColumn”)

    ————————–

    @Entity
    @Table(name = "STUDENT")
    @Inheritance(strategy = InheritanceType.JOINED)
    public class Student {
    ...
    }
    
    @Entity
    @PrimaryKeyJoinColumn(name="ID")
    public class Undergraduate extends Student {
    	private int id;
    ...
    }
    

    JAVA: Registration form with Spring

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    	<display-name>Registration Form</display-name>
    	<welcome-file-list>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
      
    	<servlet>
    		<servlet-name>mvc-dispatcher</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>/WEB-INF/config/spring-config.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
      
    	<servlet-mapping>
    		<servlet-name>mvc-dispatcher</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
      
    </web-app>
    

    spring.config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="
    	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    	
    	<context:component-scan base-package="sam.reg" />
    	
    	<mvc:annotation-driven />
    	
    	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="order" value="1"/>
    		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    		<property name="prefix">
    			<value>/WEB-INF/pages/</value>
    		</property>
    		<property name="suffix">
    			<value>.jsp</value>
    		</property>
    	</bean>
    	
    	<!-- <bean class="sam.reg.util.StudentValidator" /> -->
    	
    	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    		<property name="basename" value="resources/Student" />
    	</bean>
    	
    </beans>
    

    Student.properties WEB-INF/classes/resources/Student.properties

    required.name.student.name=Student name required
    

    Student.java

    package sam.reg.domain;
    
    public class Student {
    
    	private String name;
    	private short age;
    	private byte gender;
    	private String phone;
    	private String email;
    	private String password;
    	private String degree;
    	private String department;
    
    	// getters and setters ....
    }
    

    StudentController.java

    package sam.reg.web;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.support.SessionStatus;
    
    import sam.reg.domain.Student;
    import sam.reg.util.StudentValidator;
    
    @Controller
    @RequestMapping(value = "/student")
    public class StudentController {
    
    	private StudentValidator validator;
    
    	@Autowired
    	public void setValidator(StudentValidator validator) {
    		this.validator = validator;
    	}
    
    	// initForm
    	@RequestMapping(value = "", method = RequestMethod.GET)
    	public String initForm(ModelMap model) {
    		Student student = new Student();
    		model.addAttribute("student", student);
    		return "reg-form";
    	}
    
    	// processForm
    	@RequestMapping(value = "", method = RequestMethod.POST)
    	public String processForm(ModelMap model,
    			@ModelAttribute("student") Student student, BindingResult result,
    			SessionStatus status) {
    		validator.validate(student, result);
    		if (result.hasErrors()) {
    			return "reg-form";
    		} else {
    			status.setComplete();
    			return "successful";
    		}
    	}
    
    	// degree List
    	@ModelAttribute("degreeList")
    	public List<String> populateDegreeList() {
    		List<String> list = new ArrayList<String>();
    		list.add("B.Sc.");
    		list.add("M.Sc.");
    		return list;
    	}
    
    	// department list
    	@ModelAttribute("departmentList")
    	public List<String> populateDepartmentList() {
    		List<String> list = new ArrayList<String>();
    		list.add("IT");
    		list.add("Management");
    		return list;
    	}
    
    }
    

    StudentValidator.java

    package sam.reg.util;
    
    import org.springframework.stereotype.Component;
    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.validation.Validator;
    
    import sam.reg.domain.Student;
    
    @Component
    public class StudentValidator implements Validator {
    
    	@Override
    	public boolean supports(Class<?> arg0) {
    		return Student.class.isAssignableFrom(arg0);
    	}
    
    	@Override
    	public void validate(Object arg0, Errors arg1) {
    		Student student = (Student) arg0;
    		ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "required.name");
    	}
    
    }
    

    reg-form.jsp

    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <html>
    <head>
    <title>Student Registration Form</title>
    
    <style type="text/css">
    .error {
    	color: red;
    }
    </style>
    
    <script type="text/javascript">
    	function clearFields() {
    		document.forms["reg-form"]["name"].value = "";
    		document.forms["reg-form"]["age"].value = "";
    		//document.forms["reg-form"]["gender"].checked = false;
    		document.forms["reg-form"]["phone"].value = "";
    		document.forms["reg-form"]["email"].value = "";
    		document.forms["reg-form"]["password"].value = "";
    		document.forms["reg-form"]["degree"].selectedIndex = 0;
    		document.forms["reg-form"]["department"].selectedIndex = 0;
    	}
    
    	function validateFields() {
    		return true;
    	}
    </script>
    
    </head>
    <body>
    	<form:form method="POST" commandName="student" name="reg-form"
    		onsubmit="return validateFields()">
    		<table>
    			<tr>
    				<td colspan="3"><form:errors path="*" cssClass="error" /></td>
    			<tr>
    				<!-- NAME -->
    			<tr>
    				<td></td>
    				<td><form:input path="name" /></td>
    				<td><form:errors path="name" cssClass="error" /></td>
    			<tr>
    				<!-- AGE -->
    			<tr>
    				<td></td>
    				<td><form:input path="age" /></td>
    				<td><form:errors path="age" cssClass="error" /></td>
    			<tr>
    				<!-- GENDER -->
    			<tr>
    				<td></td>
    				<td>
    				<form:radiobutton path="gender" value="0" label="Female" />
    				<form:radiobutton path="gender" value="1" label="Male" />				
    				</td>
    				<td></td>
    			<tr>
    				<!-- PHONE -->
    			<tr>
    				<td></td>
    				<td><form:input path="phone" /></td>
    				<td><form:errors path="phone" cssClass="error" /></td>
    			<tr>
    				<!-- EMAIL -->
    			<tr>
    				<td></td>
    				<td><form:input path="email" /></td>
    				<td><form:errors path="email" cssClass="error" /></td>
    			<tr>
    				<!-- PASSWORD -->
    			<tr>
    				<td></td>
    				<td><form:input path="password" /></td>
    				<td><form:errors path="password" cssClass="error" /></td>
    			<tr>
    				<!-- DEGREE -->
    			<tr>
    				<td></td>
    				<td><form:select path="degree">
    						<form:options items="${degreeList}" />
    					</form:select></td>
    				<td></td>
    			<tr>
    				<!-- DEPARTMENT -->
    			<tr>
    				<td></td>
    				<td><form:select path="department">
    						<form:options items="${departmentList}" />
    					</form:select></td>
    				<td></td>
    			<tr>
    			<tr>
    				<td></td>
    				<td><input type="submit" value="Submit" /> <input
    					type="button" value="Clear" onclick="clearFields()" /></td>
    				<td></td>
    			<tr>
    		</table>
    	</form:form>
    </body>
    </html>
    

    References
    Mkyong

    Form : Basic

    student-registration.jsp

    
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
    	<jsp:directive.page language="java"
    		contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" />
    	<jsp:text>
    		<![CDATA[ <?xml version="1.0" encoding="ISO-8859-1" ?> ]]>
    	</jsp:text>
    	<jsp:text>
    		<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
    	</jsp:text>
    	<html xmlns="http://www.w3.org/1999/xhtml">
    <SCRIPT type="text/javascript">
    	function clearFields() {
    		document.forms["reg-form"]["name"].value = "";
    		document.forms["reg-form"]["age"].value = "";
    		document.forms["reg-form"]["gender"].value = "";
    		document.forms["reg-form"]["email"].value = "";
    	}
    
    	function validateForm() {
    		var name = document.forms["reg-form"]["name"].value;
    		if (name == null || name == "") {
    			alert("Name must be filled out");
    			return false;
    		}
    		return false;
    	}
    </SCRIPT>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Student Registration Form</title>
    </head>
    <body>
    	<FORM action="student-register.do" method="post" name="reg-form"
    		onsubmit="return validateForm()">
    		<TABLE border="1" align="center">
    			<TR>
    				<TD></TD>
    				<TD>${message}</TD>
    			</TR>
    			<TR>
    				<TD>Name</TD>
    				<TD><INPUT type="text" name="name" /></TD>
    			</TR>
    			<TR>
    				<TD>Age</TD>
    				<TD><INPUT type="text" name="age" /></TD>
    			</TR>
    			<TR>
    				<TD>Gender</TD>
    				<TD><INPUT type="text" name="gender" /></TD>
    			</TR>
    			<TR>
    				<TD>Email</TD>
    				<TD><INPUT type="text" name="email" /></TD>
    			</TR>
    			<TR>
    				<TD></TD>
    				<TD><INPUT type="submit" value="Submit" /> <INPUT
    					type="button" value="Clear" onclick="clearFields();" /></TD>
    			</TR>
    		</TABLE>
    	</FORM>
    </body>
    	</html>
    </jsp:root>
    
    

    StudentRegistrationController.java

    
    package jkcs.basic;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.ws.Response;
    
    import org.apache.catalina.connector.Request;
    
    /**
     * Servlet implementation class StudentRegistrationController
     */
    public class StudentRegistrationController extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	/**
    	 * @see HttpServlet#HttpServlet()
    	 */
    	public StudentRegistrationController() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doGet(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		response.getWriter().write("S T U D E N T");
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    	 *      response)
    	 */
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String name = request.getParameter("name");
    		String age = request.getParameter("age");
    		String gender = request.getParameter("gender");
    		String email = request.getParameter("email");
    
    		// validation
    		boolean validForm = false;
    		// name
    		if (checkEmpty(name) && checkEmpty(age) && checkEmpty(gender)
    				&& checkEmpty(email)) {
    			// further validation
    			validForm = true;
    		} else {
    			response.getWriter().write("errors");
    			validForm = false;
    		}
    
    		RequestDispatcher view = request
    				.getRequestDispatcher("student-registration.jsp");
    		if (validForm) {
    			request.setAttribute("message", "Thank you!");
    		} else {
    			request.setAttribute("message",
    					"Please recheck and submit");
    		}
    
    		view.forward(request, response);
    
    	}
    
    	public boolean checkEmpty(String data) {
    		if (data.equals("") || data == null) {
    			return false;
    		}
    		// more validation
    		return true;
    	}
    
    }
    
    

    Reference

    Hibernate : Issues

    Many vacancies have one Employer,

    I tried to map it with something like below,

    @ManyToOne
    @Column(name="OWNER")
    public Employer getOwner() {
    	return owner;
    }
    

    @Column(s) not allowed on a @ManyToOne property

    According to the above mentioned post, solution…

    @ManyToOne
    @JoinColumn(name="OWNER")
    public Employer getOwner() {
    	return owner;
    }
    

    Java : OOP concepts applied

    TextEntity.java

    public interface TextEntity {
    	public void print();
    }
    

    TextContainer.java

    import java.util.List;
    
    public abstract class TextContainer implements TextEntity {
    
    	protected List<TextEntity> textEntities;
    	protected String title;
    	
    	public void addEntity(TextEntity textEntity) {
    		textEntities.add(textEntity);
    	}
    
    	public void print() {
    		for(TextEntity textEntity : textEntities) {
    			textEntity.print();
    		}
    	}
    }
    

    Book.java

    import java.util.ArrayList;
    
    public class Book extends TextContainer {
    
    	public Book(String title) {
    		this.title = title;
    		this.textEntities = new ArrayList<TextEntity>();
    	}
    	
    	public void print() {
    		System.out.println("- Book : " + this.title);
    		super.print();
    	}
    
    }
    

    Chapter.java

    import java.util.ArrayList;
    
    public class Chapter extends TextContainer {
    	
    	public Chapter(String title) {
    		this.title = title;
    		this.textEntities = new ArrayList<TextEntity>();
    	}
    	
    	public void print() {
    		System.out.println("\tChapter : " + this.title);
    		super.print();
    	}
    	
    }
    

    Section.java

    import java.util.ArrayList;
    
    public class Section extends TextContainer {
    
    	public Section(String title) {
    		this.title = title;
    		this.textEntities = new ArrayList<TextEntity>();
    	}
    
    	public void print() {
    		System.out.println("\t\tSection : " + this.title);
    	}
    	
    }
    

    Main.java

    import java.util.List;
    import java.util.ArrayList;
    
    public class Main {
    	public static void main(String[] args) {
    		
    		// Book 1 : Chapter 1
    		TextContainer chapterA1 = new Chapter("1");		
    		chapterA1.addEntity(new Section("A"));		
    		chapterA1.addEntity(new Section("B"));
    		// Book 1 : Chapter 2
    		TextContainer chapterA2 = new Chapter("2");
    		chapterA2.addEntity(new Section("A"));		
    		chapterA2.addEntity(new Section("B"));		
    		// Add chapters
    		TextContainer bookA = new Book("ABC");
    		bookA.addEntity(chapterA1);
    		bookA.addEntity(chapterA2);
    		
    		// Book 2 : Chapter 1
    		TextContainer chapterB1 = new Chapter("1");		
    		chapterB1.addEntity(new Section("A"));		
    		chapterB1.addEntity(new Section("B"));
    		// Book 2 : Chapter 2
    		TextContainer chapterB2 = new Chapter("1");		
    		chapterB2.addEntity(new Section("A"));		
    		chapterB2.addEntity(new Section("B"));
    		// Add chapters
    		TextContainer bookB = new Book("XYZ");
    		bookB.addEntity(chapterB1);
    		bookB.addEntity(chapterB2);
    
    		List<TextContainer> bookList = new ArrayList<TextContainer>();		
    		bookList.add(bookA);
    		bookList.add(bookB);
    		
    		// Print
    		for(TextContainer book : bookList) {
    			book.print();
    		}
    	
    	}
    }	
    

    run.bat

    javac Main.java
    java Main
    pause
    
    Tagged

    JAVA: Hibernate Basics

    Student.java

    package sam.hb;
    
    public class Student {
    
    	private int id;
    	private String firstName;
    	private String lastName;
    
    	// zero arguments
    	public Student() {
    	}
    
    	public Student(String firstName, String lastName) {
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	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;
    	}
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result
    				+ ((firstName == null) ? 0 : firstName.hashCode());
    		result = prime * result + id;
    		result = prime * result
    				+ ((lastName == null) ? 0 : lastName.hashCode());
    		return result;
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (getClass() != obj.getClass())
    			return false;
    		Student other = (Student) obj;
    		if (firstName == null) {
    			if (other.firstName != null)
    				return false;
    		} else if (!firstName.equals(other.firstName))
    			return false;
    		if (id != other.id)
    			return false;
    		if (lastName == null) {
    			if (other.lastName != null)
    				return false;
    		} else if (!lastName.equals(other.lastName))
    			return false;
    		return true;
    	}
    
    }
    

    Persister.java

    package sam.hb;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    public class Persister {
    
    	public static void main(String[] args) throws Exception {
    		SessionFactory factory = configureSessionFactory();
    		Session session = factory.openSession();
    		// starting a transaction
    		Transaction tx = session.beginTransaction();
    		// persisting…
    		Student student = new Student("Sam", "Jay");
    		session.save(student);
    		// commiting the transaction
    		tx.commit();
    		session.close();
    	}
    
    	private static SessionFactory configureSessionFactory()
    			throws HibernateException {
    		Configuration configuration = new Configuration();
    		configuration.configure();
    		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
    				.applySettings(configuration.getProperties())
    				.buildServiceRegistry();
    		SessionFactory sessionFactory = configuration
    				.buildSessionFactory(serviceRegistry);
    		return sessionFactory;
    	}
    
    }
    

    Student.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="sam.hb.Student" table="STUDENT">
    		<id name="id" type="int" column="id">
    			<generator class="increment" />
    		</id>
    		<property name="firstName" column="FIRST_NAME" type="string" />
    		<property name="lastName" column="LAST_NAME" type="string" />
    	</class>
    </hibernate-mapping>
    

    hibernate.cfg.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                             "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
     <session-factory name="">
      <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
      <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost/hiberdb</property>
      <property name="hibernate.connection.username">sa</property>
      <property name="hibernate.connection.password"/>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <!-- Mapping files -->
      <mapping class="sam.hb.Student" resource="sam/hb/Student.hbm.xml"/>
     </session-factory>
    </hibernate-configuration>