AppFuse Document (3) - Create DAO

xiaoxiao2021-03-06  40

Create DAO

This chapter will show you how to create Java objects that use data to express Table and a Java class that persistent data.

About this chapter

This section will show you how to create a new table and how to create Java code accessed on this table.

We will create an object, and some of the classes that persist (add, modify, delete) to the database. According to Java's practice, we call this object for Plain Old Java Object (Pojo

This object mainly represents a table in the database. Other classes are:

· A Data Access Object (DAO

), An interface

And a hibernate implementation class.

· A JUnit that tests whether our Dao is working properly

class

Note: If you are using MySQL and want to use Transactions (Which You Probably Will).

You must use the InnoDB table. To add the following to the mysql configuration file (My.cnf or C: /Windows/my.ini)

[mysqld]

Default-Table-Type = InnoDB

Appfuse uses hibernate

As the default data persistence layer. Hibernate is an object / relationship (O / R) framework that allows you to associate a Java object. It allows you to easily perform crud (Create, Retrieve, Update, Delete).

Let's start to create an Object, Dao, and Test test cases!

content

· [1] Create a new Object, add xdoclet tag

· [2] Use ANT to create a new table according to the object

· [3] Create a new daotest to run Junit, test your DAO

· [4] Create a new DAO to execute the CRUD of the object

· [5] Configuring Spring for Person objects and Persondao

· [6] Run daotest

Create a new Object to add xdoclet tag

The first thing we have to do is to create a persistent object. We will create a simple "Person" object in the src / dao / ** / model directory, which has ID, firstname, and lastname. (LTF: To ensure that the getter of the ID attribute of the object is the first method of the current class, otherwise the generated JSP page may have a script error)

package org.appfuse.model; 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 * /}

This class should inherit BaseObject

BaseObject has 3 abstract methods: (Equals (), havehcode () and toString ()), these three methods must be implemented in Person. The first 2 method is hibernate necessary. The easiest implementation method is to use CommonClipse

It automatically generates these methods.

Now we have created this Pojo object, we need to add an XDoclet tag to generate the Hibernate mapping file. Hibernate establishes an object (attribute) → table (column) mapping with this mapping file.

The first step, we add a @ hibernate.class

Tag, tell Hibernate what table is related to this object:

/ ** * @ hibernate.class table = "person" * / public class person extends BaseObject {We have to add a primary key mapping, otherwise xDoclet will not be properly executed correctly when generating mapping files. Note: All @ hibernate. * Tag must be placed in the javadoc of your Pojo's Getter.

/ ** * @Return Returns the ID. * @ Hibernate.id column = "id" * generator-class = "increment" unsaved-value = "null" * / public long positionId () {returnid;

}

I use generator-class = "increment" instead of generate-class = "native" because I found some questions when using "native". If you plan to use MySQL, I recommend you to use the Native value. This article uses increment.

Use ANT to create a new table according to objects

Now we can create "Ant Setup-DB" to create a Person table! This task will create a Person.hbm.xml file and a table called "Person". From the ANT console, you can see the schema for the table you created for you:

[SchemaExport] Create Table Person

[SchemaExport] ID Bigint Not Null,

[SchemaExport] Primary Key (ID)

[SchemaExport]);

If you want to see Hibernate for your Person.hbm.xml, you can find it from the build / Dao / Gen / ** / Model directory. Here is the content of Person.hbm.xml so far:

Add @ hibernate.property to other columns (first_name, last_name)

label:

/ ** * @ hibernate.property column = "first_name" length = "50" * / public String getFirstName () {return this.firstName;} / ** * @ hibernate.property column = "last_name" length = "50" * / Public string getlastname () {return this.lastname;}

In this example, the only reason for adding a column property is: the list of column names and objects of the object are inconsistent. If they are consistent, they don't need to add a column property. See @ hibernate.property if you want to know other properties of XDoclet's Hibernate.

.

Run "Ant Setup-DB" again to generate a new column.

[SchemaExport] Create Table Person

[SchemaExport] ID Bigint Not Null,

[SchemaExport] first_name varchar (50),

[Schemaexport] last_name varchar (50),

[SchemaExport] Primary Key (ID) [SchemaExport]);

If you want to change the length of the column, change the @ hibernate.property tag for the length property. If you want it to be a must null, then you have to add NOT-NULL = "True."

Create a new daotest to run Junit, test your DAO

Note: Because I encountered a lot of problems during the code of this article, I want you to know such a tool: Lance Lavandowska

Daogen created

It can be placed in the "Extras" directory to generate DAO and Manager mentioned in this article. If you like it, you should be updated to 1.6 . The main reason is: I don't want to deal with "What Did i Just Generate"?

- Through this document, you should learn how the entire program is running.

We now create a daotest to test our Dao work. "Wait a minute, we haven't created a DAO!", You are right, but I discover Test-Driven Developments

(Test Drive Development) can bring higher quality software. A few years ago, I thought that the test class before writing is a pig food (bad thing). It looks stupid. However, when I tried to do it, I found it very good! The only reason I fill all test drivers in this article is that I found that the method of test-driven development can bring higher efficiency and better quality software.

let's start! We created classes in Test / Dao / ** / DAO to create classes in Persondaotest.java. This class should inherit BaseDaOTestCase

(This class already exists in the package). BaseDaOTestCase class is used to load Spring's

ApplicationContext (because Spring and Layer Bind together) and an optional .properties file (and ResourceBundle file with your * Test.class). In this example, if you put a persotest.properties file in the directory where PersondaOTest.java is located, the properties of this file can be accessed through a "RB" variable.

I usually replicate (Open → Save as) an existing test file (such as UserDaotest.java), then use [PP] Erson to find / override [UU] Ser.

package org.appfuse.dao; import org.appfuse.model.Person; import org.springframework.dao.DataAccessException; public class PersonDAOTest extends BaseDAOTestCase {private Person person = null; private PersonDAO dao = null; protected void setUp () throws Exception {Super.Setup (); DAO = (PERSONDAO) CTX.getBean ("Persondao");} protected void teardown () throws exception {super.teardown () () (); DAO = null;}}

The above code is a basic initialization, destroying the JUnit test of the Persondao object. The "CTX" object is a reference to Spring's ApplicationContext, which is initialized in the static code block of the BaseDaOTestCase's class.

Now we have to test whether our Dao object's crud (Create, Retrieve, Update, delete) work. In order to achieve this, we create a method of "TEST" (all lowercase).. The scope of these methods PUBLIC, the return type is Void, and there is no parameter. They will be called by the task of the build.xml file used by Ant.

Below is a simple test of crudation. It is necessary to keep in mind that each method (also as a test) creates himself. Add the following method in the persotest.java file:

Public void testgetPerson () throws exception {person = new person (); person.SetFirstName ("matt"); person.SetLastName ("Raible"); DAO.SAVEPERSON (PERSON); AssertNotNull ()); Person.GetId (); person = DAO.GETPERSON (Person.GetId ()); Assertequals (Person.GetfirstName (), "matt");} public void testsavePerson () throws exception {person = DAO.GETPERSON (New long (1)); person.setfirstname ("Matt"); Person.SetLastName ("Last Name Updated"); DAO.SAVEPERSON (PERSON); if (log.isdebugeload ()) {log.debug ("Updated Person:" Person);} Assertequals (Person) .getLastName (), "Last Name Updated");} public void testAddAndRemovePerson () throws Exception {person = new Person (); person.setFirstName ( "Bill"); person.setLastName ( "Joy"); dao.savePerson ( Person; Assertequals (Person.GetFirstName (), "Bill"); assertNotNull (Person.GetId ()); if (log.Indebuge Nabled ()) {log.debug ("Removing Person ..."); DAO.REMOVEPERSON (Person.GetId ()); try {person = DAO.GETPERSON (Person.GetId ()); Fail ("Person Found IN database ");} catch (DataAccessException DAE) {log.debug (" Excected Exception: " DAE.GetMessage ()); AssertNotnull (DAE);}} In the TestgetPerson method, we create a Person object and then call a call Get. Usually I will enter a test record I always used in the database. Due to dbunit

Will load data before our test cases, so you can add a new table / record to the metadata / SQL / Sample-Data.xml file:

id

first_name last_name

1

Matt

Raible

Using this method, you can achieve the purpose of "CREATE New" in the TestgetPerson method. If you prefer to add a record directly to the database through SQL or GUI,

Then you can use "Ant DB-EXPORT" reconstruction (Rebuild) Sample-Data.xm file,

Then perform "CP DB-export.xml metadata / SQL / Sample-Data.xml".

In the above example, Person.Set * (Value) to assemble (PERSON.SET * (VALUE) is called before saving it. This example looks simple, but if the persistent object has more than 10 items (Not-Null = "True" field, this process will be tired of [cumbersome]. That's why I want to create a resourcebundle file in BaseDaotestCase. Create a personDaotest.properties file in the directory of the persotest.java file, then define properties - value:

I tend to do hard-code in the Java code - but use .properties file is an alternative to a large number of objects work better.

Firstname = matt

Lastname = raille

This way we can use the baseDaotestcase.populate (java.lang.Object) method to achieve the same purpose, no need to call the Person.Set * method to assemble (Populate) your object:

Person = New Person (); Person = (Person) Populate (Person);

At this point, PersondaOTest still can't be compiled, because there is no Persondao.class in our classpath, now let's create it. Persondao.java is an interface, and the Persondaohibernate.java class is an implementation of this interface using Hibernate. Let us move forward, create them!

Create a new DAO to execute the CRUD of the object

We created a personDao.java interface in the directory src / dao / ** / DAO, then specify the CRUD method that implements the class that implements this interface. In the following category I dropped the Javadoc comment showing this purpose.

package org.appfuse.dao; import org.appfuse.model.Person; public interface PersonDAO extends DAO {public Person getPerson (Long personId); public void savePerson (Person person); public void removePerson (Long personId);}

Please note: Method Signature is declared in Method Signature, I have not thrown out. This is because Spring

It provides powerful features, which use runtimeException to encapsulate exceptions. Now you can compile all the files in the directory src / Dao and Test / Dao using "Ant Compile-Dao".

However, if you try to run "Ant Test-Dao -dtestcase = Persondao", you will see an error: no bean named 'personDao' is defined. This is an error thrown - prompt us to specify a bean called Persondao in ApplicationContext-Hibernate.xml. Before we do this, we have to create the implementation class of Persondao. The ANT task running the DAO test is called "Test-Dao". If you pass the TestCase parameter (using -dtestcase = name), the optional value of the parameter is Person, Persondao, or Persondurtest, which will look for ** / * $ {testcase} * - all of this will execute the PersondaOTest class.

Now, start to create a Persondaohibernate class, which implements the method specified in the interface Persondao and then uses Hibernate to get / save / delete the Person object. To achieve this, we must create a new class Persondaohibernate.java in the directory src / dao / ** / dao / hibernate. It should inherit Basedaohibernate

And implement interface personDao. BREVITY [short]

package org.appfuse.dao.hibernate; import org.appfuse.model.Person; import org.appfuse.dao.PersonDAO; import org.springframework.orm.ObjectRetrievalFailureException; public class PersonDAOHibernate extends BaseDAOHibernate implements PersonDAO {public Person getPerson (Long id ) {Person person = (Person) getHibernateTemplate () get (Person.class, id);. if (person == null) {throw new ObjectRetrievalFailureException (Person.class, id);} return person;} public void savePerson (Person Person) {gethibernateTemplate (). SaveorUpdate (Person);} PUBLIC VOID RELEPERSON (LONG ID) {// Object Must Be Loaded Before It Can Be deleted gethateTemplate (). delete (GetPerson (ID));}}

Now, if you try to run "Ant Test-Dao -dtestcase = Persondao", you will still get the same error. We need to configure Spring, let it know that personDaohibernate is the implementation class of the interface person, we also tell it about some information about the Person object.

Configuring Spring for Person objects and Persondao

First, we have to tell Spring: Where is the hibernate map file required. Open SRC / DAO / ** / DAO / Hibernate / ApplicationContext-Hibernate.xml, add Person.hbm.xml to the code block below:

ORG / AppFUSE / Model / Person.hbm.xml ORG / AppFUse / model / role.hbm.xml Org / appfuse / model / user.hbm.xml ORG / AppFUse / model / usercookie.hbm.xml

In order to bind personDaohibernate to Persondao, we add some XML code at the bottom of this file:

< / Property>

You can also add autowire = "byname" in the section, and then get the RID of the "SessionFactory" property. I personally like to rely on my Objects Documented (in XML).

Run daotest

Save all your files you have modified, and try to run "Ant Test-Dao -dtestcase = Persondao" once or more.

Yeah Baby, Yeah:

Build SuccessFultotal Time: 9 Seconds

Next:

Part II: Create Manager -

How to create

Business facade.

These ones

Façade

Used to connect the front end and

DAO

Communication between layers.

转载请注明原文地址:https://www.9cbs.com/read-54393.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.044, SQL: 9