appFuse2.x第三篇--Persistence

本文介绍如何使用Java创建Plain Old Java Object (POJO),并利用JPA注解将其映射到数据库表中。同时介绍了如何通过Maven自动生成数据库表结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This tutorial will show you how to create a new database table and the Java code to access that table.

You will create an object and then some more classes to persist (save/retrieve/delete) that object from the database. In Java speak, this object is called a Plain Old Java Object (POJO). This object basically represents a database table. With AppFuse 1.x, you typically created a DAO and JUnit Test to persist this POJO. However, with AppFuse 2.x, there is a Generics-based DAO and Manager that will CRUD all objects for you. The only time you'll need to create DAOs is when you want custom behavior or if you need finders.

AppFuse uses Hibernate for its default persistence layer. Hibernate is an Object/Relational (O/R) Framework that allows you to relate your Java Objects to database tables. It allows you to very easily perform CRUD (Create, Retrieve, Update, Delete) on your objects.

iBATIS and JPA
You can also use iBATIS or JPA as a persistence framework option. To use iBATIS with AppFuse, see the using iBATIS tutorial. To use JPA implementation, see the using JPA tutorial.

To get started creating a new Object and table in AppFuse's project structure, please complete the instructions below.

Table of Contents

  1. Create a new POJO and add JPA Annotations
  2. Create a new database table from the object using Maven

Create a new POJO and add JPA Annotations

The first thing you need to do is create an object to persist. Create a simple "Person" object (in the src/main/java/**/model directory for the basic archetypes or the core/src/main/java/**/model directory for the modular archetypes) that has an id, a firstName and a lastName (as properties). For recommend package-naming conventions, see the FAQ. These tutorials use "org.appfuse.tutorial" as the root package name.

package org.appfuse.tutorial.model;  
 
import org.appfuse.model.BaseObject;  
 
import javax.persistence.Entity;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
import javax.persistence.GeneratedValue;  
import javax.persistence.Column;  
 
public class Person extends BaseObject {  
    private Long id;  
    private String firstName;  
    private String lastName;  
 
    /*
     Generate your getters and setters using your favorite IDE: 
     In Eclipse:
     Right-click -> Source -> Generate Getters and Setters
    */ 
Extending BaseObject is optional, but recommended as a good practice to force creation of toString(), equals() and hashCode() methods. If you plan to put this object into the user's session, or expose it through a web service, you should implement java.io.Serializable as well.

To generate toString(), equals() and hashCode() methods, you can use Commonclipse. More information on using this tool can be found on Lee Grey's site. Another Eclipse Plugin you can use is Commons4E. When generating or writing equals() and hashCode() methods, you don't want to include your object's primary key. See Hibernate's Equals and Hascode for more information.

IntelliJ Users
If you're using IntelliJ IDEA, you can generate equals() and hashCode(), but not toString(). There is a ToStringPlugin that works reasonably well.

Now that you have this POJO created, you need to add JPA annotations. These annotations are used by Hibernate to map objects → tables and properties (variables) → columns.

If you're new to Hibernate and Annotations, you might want to read An Introduction to Hibernate 3 Annotations by John Ferguson Smart.

First of all, add an @Entity annotation that signifies what table this object relates to. The "name" is optional; the class name is used if it's not specified. Make sure you import annotations from javax.persistence.* rather than from Hibernate.

@Entity  
public class Person extends BaseObject { 
If you specify a name value for your @Entity annotation (for example @Entity(name="person")), this will be the alias for HQL queries. If you don't specify this value, the name will match the short name of your class (Person). If you want to change the table name that's generated, use the @Table annotation with a "name" value.

You also have to add an @Id annotation to signify the primary key. The @GeneratedValue annotation should also be specified to indicate the primary key generation strategy.

@Id @GeneratedValue(strategy = GenerationType.AUTO)   
public Long getId() {  
    return this.id;  

For the rest of the fields, you aren't required to annotate them unless you want to 1) exclude them from being persisted (with @Transient) or 2) want to change their column name or other attributes. To change the column names, use the @Column annotation. Add the @Column annotation to both the getFirstName() and getLastName() methods.

@Column(name="first_name", length=50)  
public String getFirstName() {  
    return this.firstName;  
}  
...
@Column(name="last_name", length=50)  
public String getLastName() {  
    return this.lastName;  
Annotations on fields
You can also put JPA annotations on fields instead of getters. However, you should be aware that if you add field-level annotations, method-level annotations will be ignored.

Create a new database table from the object using Maven

Open src/main/resources/hibernate.cfg.xml for the basic archetypes (or core/src/main/resources/hibernate.cfg.xml for the modular archetypes) and register your Person object with the following XML:

<mapping class="org.appfuse.tutorial.model.Person"/> 

Save the file and run mvn test-compile hibernate3:hbm2ddl from the command line. For modular projects, make sure you run this command from the "core" directory. This will generate your database schema with the "person" table included.

create table person (id bigint not null auto_increment, first_name varchar(50), primary key (id)) type=InnoDB; 

After you've created a POJO and generated a schema from it, how do you persist that object? AppFuse ships with GenericDao implementations that makes it possible CRUD any object. In addition to this Generics-based class, there is a UniversalDao that does the same thing. The major difference between the two is you'll need to cast to your specified type for the UniversalDao. However, it also doesn't require you to define any new Spring beans, so there's a benefits and drawbacks. For these tutorials, you will learn how to program using the GenericDao.

Please choose the persistence framework you'd like to use to continue:

If you don't know which is better for your project, please read Hibernate vs. iBATIS.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值