EJB 3.0 Development Guide-Entity Bean (1)
Developing entity beans in ejb3.0 is very simple. You can program it like developing Java Beans, with only a small amount of comments required. An entity bean does not need to implement the home interface or remote or local interface.
Entity beans are generated, searched, combined with the persistent layer, and withdrawn from the persistent layer through entitymanager.
JBoss's ejb3.0 architecture is built on hibernate.
Note:
@ Entity: If you want to create an object Bean class, you must add this annotation to the class to tell the container that the class is an object bean. The primary key of this bean is specified by @ ID.
The declaration of this annotation is as follows:
@ Target (type) @ retention (runtime) Public @ interface entity { String name () Default ""; Entitytype () default CMP; Accesstype access () default property; Int version () default 3; } |
Name is used to specify the name of the object bean. By default, it is the same as the class name.
Entitytype is used to specify whether the bean is a persistent Entity Bean managed by the container or a persistent Entity Bean managed by the bean. It can be CMP or BMP.
Accesstype is used to specify how the container accesses the persistent data of this EJB. Property is used to tell the container to use GET/set to access persistent data (that is, data without transient annotation). Filed tells the container to directly access the field. The field should be declared as the protected type.
To be provided to clients such as other session beans, this bean should implement the serializable interface.
The Entity Bean must be constructed using a non-parameter constructor.
Persistent attributes include: Basic Java types (INT, long, etc.), String, biginteger, bigdecimal, and Java. util. date, calendar, Java. SQL. date, Java. SQL. time, Java. SQL. timestamp, byte [], char [], other Entity Bean types, and other entity bean collections (collection, set, list not supported ).
@ Table
It is used to specify the main table used by this entity bean. Other tables may be required. For more information, see the following section. The uniqueconstraint annotation is used to add constraints.
@ ID
Specifies the primary key of the object bean. It can be generated in multiple ways:
· Table: Containers use the underlying data table to ensure uniqueness.
· Sequence: Use the sequence column of the database to ensure uniqueness.
· Identity: use the database's indentit column to ensure uniqueness
· Auto: The container selects an appropriate method to ensure the unique
· None: the container is not responsible for generating the primary key, which is completed by the calling program.
@ Onetoworkflow
The two entity beans may have one-to-many, many-to-one, one-to-one, and many-to-many relationships. The following two relations are described in the following example.
For example, there is a one-to-many relationship between the student and the scores of each course.
In ejb3.0, one-to-many associations must be bidirectional. That is to say, there must be multiple-to-one associations that correspond to each other.
The onetoworkflow annotation declaration is as follows:
@ Target ({method, field}) @ retention (runtime) Public @ interface onetoworkflow { String targetentity () Default ""; Cascadetype [] cascade () default {}; Fetchtype fetch () default lazy; } |
When we use this annotation as a get method annotation, if we use the common programming of JDK and return the collection <target object type>, we do not need to specify the targetentity type, otherwise, if the returned type is declared as a normal collection, the targetentity type must be declared.
Cascadetype specifies how the object associated with this object needs to be processed when this entity bean is created or merge:
· Merge: when the primary entity bean is merge, the associated entity bean is also merge
· Create: when the primary entity bean is created, the associated entity bean is also created
· Remove: when the primary entity bean is evict, the associated entity bean is also evict
· All: including the above cases
Fetchtype specifies the way to read data: lazy or eager. Lazy obtains the related entity bean from the database only when it is accessed for the first time. The Eager is very active and is generated together with the main entity bean.
@ Manytoone
We know that one-to-many associations are bidirectional. The method annotated by manytoone must be declared in the associated object bean.
@ Joincolumn
We know that two entities can be associated, but a column needs to be specified as a foreign key in the table. If no name is specified, the primary keys in the primary table and the columns in the table have the same names as the Foreign keys. If referencedcolumnname is not specified, the foreign key is considered to be the primary key of the secondary table.
@ Joincolumns
Used to indicate that the primary key complies with the primary key, which is described in later sections.
This example mainly contains the following files. This example mainly implements the function of managing student scores. Student is an entity bean that manages the basic information of students (names and scores of each course). The score of students is also an Entity Bean. Tacherbean is a stateless Session Bean used to call the Entity Bean. As in the previous example, we still use the client for testing.
· Student. Java: Entity Bean.
· Score. Java: Entity Bean.
· Teacher. Java: Service Interface of Session Bean
· Teacherbean. Java: Implementation class of Session Bean
· Client. Java: client class for testing EJB.
· JNDI. properties: The JNDI property file, which provides basic configuration properties for accessing jdni.
· Build. xml: ant configuration file for compiling, publishing, testing, and clearing ejbs.
The following describes the content of each file.
Student. Java
Package com. kuaff. ejb3.entity; Import javax. EJB. cascadetype; Import javax. EJB. entity; Import javax. EJB. fetchtype; Import javax. EJB. generatortype; Import javax. EJB. ID; Import javax. EJB. joincolumn; Import javax. EJB. onetoworkflow; Import javax. EJB. Table; Import java. util. arraylist; Import java. util. collection; Import java. Io. serializable; @ Entity @ Table (name = "student ") Public class student implements serializable { // Primary key Private int ID; // Student name Private string name; // Score of the student Private collection <score> scores; // Primary key automatically generated @ ID (generate = generatortype. Auto) Public int GETID () { Return ID; } Public void setid (int id) { This. ID = ID; } Public String getname () { Return name; } Public void setname (string name) { This. Name = Name; } Public void addscores (string name, int number) { If (scores = NULL) { Scores = new arraylist <score> (); } Score score = new score (); Score. setname (name ); Score. setnumber (number ); Score. setstudent (this ); Scores. Add (score ); } @ Onetomany (cascade = cascadetype. All, fetch = fetchtype. Eager) @ Joincolumn (name = "student_id ") Public Collection <score> getscores () { Return scores; } Public void setscores (collection <score> scores) { This. Scores = scores; } } |
Student. Java implements the Student Entity Bean, which provides the basic information of the student and the score of the student. The score is another entity bean. Student object bean and score object bean are one-to-many relationships. From the perspective of score, they are many-to-one relationships.
The Entity Bean needs to be annotated using @ entity. In addition, it specifies that the entity bean corresponds to the table student (by commenting @ table (name = "student ")), you can see this table in the JBoss database.
Score. Java
Package com. kuaff. ejb3.entity; Import java. Io. serializable; Import javax. EJB. entity; Import javax. EJB. generatortype; Import javax. EJB. ID; Import javax. EJB. joincolumn; Import javax. EJB. manytoone; Import javax. EJB. Table; @ Entity @ Table (name = "score ") Public class score implements serializable { Private int ID; Private string name; Private int number; Private student; // Primary key automatically generated @ ID (generate = generatortype. Auto) Public int GETID () { Return ID; } Public void setid (int id) { This. ID = ID; } Public String getname () { Return name; } Public void setname (string name) { This. Name = Name; } Public int getnumber () { Return number; } Public void setnumber (INT number) { This. Number = number; } @ Manytoone @ Joincolumn (name = "student_id ") Public student getstudent () { Return student; } Public void setstudent (Student) { This. Student = student; } } |
This entity bean stores student scores.
Teacher. Java
Package com. kuaff. ejb3.entity; Import javax. EJB. Remote; Import javax. EJB. Remove; Import java. util. Map; @ Remote Public interface teacher { Public void addscore (string studentname, Map <string, integer> map ); Public student getstudent (); @ Remove Public void leave (); } |
This session bean interface provides methods to increase scores and obtain users.
Teacherbean. Java
Package com. kuaff. ejb3.entity; Import javax. EJB. entitymanager; Import javax. EJB. Inject; Import javax. EJB. Remove; Import javax. EJB. stateful; Import java. util. Map; Import java. util. Set; @ Stateful Public class teacherbean implements teacher { @ Inject Private entitymanager manager; Private student; Public student getstudent () { Return student; } Public void addscore (string studentname, Map <string, integer> map) { If (student = NULL) { Student = new student (); } Student. setname (studentname ); Set <string> set = map. keyset (); For (string sname: Set) { Student. addscores (sname, map. Get (sname). intvalue ()); } } @ Remove Public void leave () { Manager. Create (student ); } } |
This is the implementation class of the Session Bean.
Client. Java
Package com. kuaff. ejb3.entity; Import java. util. Map; Import java. util. hashmap; Import java. util. collection; Import javax. Naming. initialcontext; Import javax. Naming. namingexception; Public class client { Public static void main (string [] ARGs) throws namingexception { Initialcontext CTX = new initialcontext (); Teacher = (teacher) CTX. Lookup (teacher. Class. getname ()); Map <string, integer> map = new hashmap <string, integer> (); Map. Put ("", new INTEGER (98 )); Map. Put ("chemistry", new INTEGER (149 )); Map. Put ("physical", new INTEGER (143 )); Teacher. addscore ("smallnest", MAP ); Student = teacher. getstudent (); String name = student. getname (); System. Out. printf ("display % S score: % N", name ); Collection <score> C = student. getscores (); For (score: C) { System. Out. printf ("% s: % S % N", score. getname (), score. getnumber () + ""); } } } |
This client increases the score of the student and the test shows the student's information.
Run run. BAT: Run-c all in the {$ jboss_home}/bin directory to start JBoss.
Http: // localhost: 8080/JMX-console/htmladaptor? Action = inspectmbean & name = JBoss % 3 aservice % 3 dhypersonic % 2 cdatabase % 3 dlocaldb, then call the startdatabasemanager () method to open the hsql management tool to manage the database.
Execute ejbjar target in the ant view of Eclipse. Alternatively, go to the project directory under the command line and execute ant ejbjar to package the compilation and release the EJB.
Run target in the ant view of Eclipse. Or enter the project directory under the command line and run ant run to test the EJB.