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:
xml version = "1.0"?>
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
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: