Spirng3.1 + Hibernate4.1 HelloWorld

Categories: Java; Tagged with: ; @ June 24th, 2012 23:20

Here is a simple example about configuration of Spring3 and Hibernate4.

1. We need define a sessionFactory bean:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/mini-liguoliang.com" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="packagesToScan" value="com.liguoliang.spring.po"></property>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>
</bean>

<context:component-scan base-package="com.liguoliang.spring"></context:component-scan>

Basically, we did there things:

  1. Define the datasource;
  2. define the session factory, we need specify the packagesToScan property, this property will scan all entity annotated class.
  3. define the context component-scan basepackage, this will scan all @Repository annotated Class, like the dao class in 4.

2. Define the Entity Class:

package com.liguoliang.spring.po;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
@javax.persistence.Table(name="ACCT_USER")
public class User {
	
	@javax.persistence.Id @GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	private String login_name;
	
	
	public String getLogin_name() {
		return login_name;
	}
	public void setLogin_name(String login_name) {
		this.login_name = login_name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public String toString() {
		return "User - " + name + " [" + id + "]";
	}
	
}

 

Note the annotation: @Entity

3. We have a table related to this entity:

image

4. In the dao class:

package com.liguoliang.spring;

import java.io.File;
import java.util.Date;

import javax.persistence.Entity;

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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.stereotype.Repository;

import com.liguoliang.spring.po.User;
@Repository
public class UserHibernateDAO {
	private SessionFactory sessionFactory;
	
	@Autowired
	public UserHibernateDAO(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public User getUserByID(int id) {
		Session session = SessionFactoryUtils.openSession(sessionFactory);
		return (User) session.get(User.class, id);
	}
}

5.  Communicate with database using DAO

We need a hibernateBean instance:

package com.liguoliang.spring.web;

@Controller
@RequestMapping(value="/spring/user")
public class ControllerUser {
	
	@Autowired
	private UserHibernateDAO userHibernateDAO;
	
	@RequestMapping(value={"", "list"})
	public String list(Model model) {
		// We just print the user info in the console.	
		System.out.println("userName: " + userHibernateDAO.getUserByID(10).toString());

		return "userList";
	}
}

When list() is called, user with the id ’10’ will be loaded by the hibernateDAO, and printed in the console.

6. Related pattern – Data Access Object

http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

Figure 9.2
Figure 9.2 Data Access Object sequence diagram

BusinessObject

The BusinessObject represents the data client. It is the object that requires access to the data source to obtain and store data. A BusinessObject may be implemented as a session bean, entity bean, or some other Java object, in addition to a servlet or helper bean that accesses the data source.

DataAccessObject

The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. The BusinessObject also delegates data load and store operations to the DataAccessObject.

DataSource

This represents a data source implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system, and so forth. A data source can also be another system (legacy/mainframe), service (B2B service or credit card bureau), or some kind of repository (LDAP).

TransferObject

This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source.

CodeReview using Crucible and JIRA 使用Crucible,JIRA进行代码审查

Categories: Development NotesJava; Tagged with: ; @ June 17th, 2012 13:41

Crucible is a tool that facilitates code review. It can be as valuable to organisations that already have a formal inspection process as it is to teams that don’t review at all.

Regular peer review is a proven process with demonstrable return on investment (ROI). The benefits vary from team to team but commonly include:

  • Identifying bugs and defects early.
  • Sharing expertise and encouraging knowledge transfer.
  • Improving system-wide knowledge.
  • Encouraging adherence to internal standards and style conventions.
  • Identifying individual strengths and weaknesses.

In my previous post “Link code change list and issue with FishEye and JIRA 关联代码变更与Issue/BacklogItem’’, test report a bug, and I submit my code change, and linked the code changes to the issue.  and now, we need to review the codes I submitted before.

  1. [David] Create a new code review by click ‘Create review’, select project, and input name, select the reviewers, and we can config weather anyone can join the review. we invite a guy named ‘admin’ to review my code.
  2. [David] Add content to review:  we can add a changeset, a file in the repositorie, or attachements, etc,.
    image
    Select the code change, and start the review.
  3. [Admin] ‘admin’ login into curcible, and see the review:
    image

    In the left tree, there are the codes need to be review, click one:
    image
    Then mark as ‘Complete’

  4. [David] And now, David can check the result:
    image
    It’s really cool!
  5. [David ]  summarize and close this review by clikc ‘summarize’ :
    image
  6. And what more, JIRA will link this review to the bug:
    image

Link code change list and issue with FishEye and JIRA 关联代码变更与Issue/BacklogItem

Categories: Java; Tagged with: ; @ June 17th, 2012 11:49

Tester report a bug, and assign to you, you coding, and commit changes, and then you go back to the bug,  wright some comments, maybe include your changelistID, then resolve the issue.

How can someone else know what’s you have done for this issue? how can you find the related code changes quickly?

FishEye can help we do this!

How FishEye can Help

FishEye opens up your repository, helping you to understand your changing source code:

  • Track changes to your own, your team’s, or everyone’s source code.
  • Choose to be notified by email and/or RSS feeds.
  • View the configurable changelog.
  • Use the powerful search functionality
  • Construct your own sophisticated queries with EyeQL and integrate the results with other tools using the FishEye API.
  • Link to any artifact in your repository: commits, diffs, directories, file histories, revisions, source lines, and search results.
  • Analyse your repository with:
    • Line graphs at every node from root to revision.
    • ‘Related Revisions’, a list of modifications from all branches, sorted by revision number.
    • File annotations for age and ownership.

And it can work perfectly with JIRA, I’ll show you the perfect feature JIRA and FishEye work seamlessly:

  1. Create a new FishEye project, you need name it and input a ‘Key’;
  2. Link this project with the JIRA project by input a JIRA project key. (or we can link project in JIRA by input a FishEye project key).
  3. Edit ‘FishEye Content’ after the creation complet: we need to config the repository path for the project.
  4. Commit some code to the repository paht, then go to the project page:
    image
    And we can view this change details:
    image
    It’s cool, right? but It can be more interesting.
  5. Someday, tester report an issue, say any one can login, the tester create a new issue in JIRA:
    image

    This bug was assigned to me.

  6. I fix this bug, and commit code change:
    image
    I want to record this change in JIRA, so that anyone concern can track my work.
    How can JIRA know which issue I’m working on?
    Here is a convention:
    use the issue id as the beginning of the comment, I commit the changes, and JIRA will capture this change list, and link to the issue: SPRIN-10.
  7. And now return to the issue page, the commit I just did has been added to the issue! Wow, that’s really cool!
    image
    We can see all related change, really helpful, not only for management, but also for developers.

Using Inner class in Java

Categories: Java; Tagged with: ; @ May 22nd, 2012 1:03

Here is the code:

package innerClasds.scjp.liguoliang.com;

import java.io.Serializable;

public class TestInnerClass {
	
	private String name = "var+TestName";
	
	public static void main(String[] args) {
		new TestInnerClass().new InnerClass().printDes();
		new TestInnerClass().testInnerClassInMethod("info");
		TestInnerClass.StaticClass.printInfo();
	}

	/**
	 * 2. Inner class in method.
	 */
	void testInnerClassInMethod(final String info) {
		// In this class, we can get any variable in the outer class, but only can access the final variables in the method.
		// The reason is(from scjp book): can not keep variables(stored in stack) can keep as long as  inner class instance (stored in the heap),
		// so the inner class only access the final variable. 
		
		// and the class access modifier:  only abstract or final is permitted
		abstract class InnerClassInMethod {
			abstract void printInfo();
		}
		
		/** 3. Anonymous class;  */
		InnerClassInMethod inMethod = new InnerClassInMethod() {
			void printInfo() {
				System.out.println(InnerClassInMethod.class + TestInnerClass.this.name + "__" + info);
			}
		};
		
		inMethod.printInfo();
	}
	
	
	/**
	 * 1. Normal inner class. can use public, protected, (default), private accessor modifier to control the scope of the class.
	 * @author Li Guoliang
	 *
	 */
	private class InnerClass extends TestInnerClass implements Serializable{
		private static final long serialVersionUID = 1L;
		//always need final, otherwise: 
		//  The field s cannot be declared static; static fields can only be declared in static or top level types
		public static final String s = "s"; 
		void printDes() {
			System.out.println("Inner" + s + " " + TestInnerClass.class);
		}
	}
	
	/**
	 * 4. Static nested class.
	 * @author Li Guoliang
	 *
	 */
	private static class StaticClass {
		static void printInfo() {
			System.out.println(StaticClass.class);
		}
	}

}

Some comments:

1. Inner Class:

can be public, protected, private, final, abstract, static, strictfp.
need an outer instance to crate the inner instance, like: new TestInnerClass().new InnerClass();
Use outClass.this to get the outer instance;

2. Inner class in method

can be public, protected, private, final, abstract, static, strictfp;
can access any property in the outer instance;
only can access final variable in the method.

3. Anonymous class

4. Static nested class
can be public, protected, private, final, abstract, static, strictfp.

here are some notes when I first learn inner class in java: >>go<<

Java: Using Assertion in Eclipse

Categories: Java; Tagged with: ; @ May 21st, 2012 0:06

Assertion:

	public static void main(String[] args) {
		int x = 10;
		assert x==100:"assertion failed!";
	}

How to determine assertion is enabled or not?

		   boolean isEnable=false;
		   assert isEnable = true;
		   if(isEnable){
		       throw new RuntimeException("Assertion shoule be enable!");
		   }

This is a bad assertion, because it change the value, If assertion is enabled, isEnable will be set to true.

How to enable assertion in Eclipse?

Debug/Run configurations > VM arguments: add “-ea” to enable it or “-da” to disable assertion.

should not used for validate parameter in public method: because anyone can use public method, and can not make sure assertion is enabled or not;

Newer Posts <-> Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.