Ejb3.0 Entity Bean (5)

Source: Internet
Author: User
Tags jboss
6.6.4 multi-to-Multi- ing
Students and teachers are many-to-many relationships. One student has multiple teachers and one teacher teaches multiple students. Multiple-to-multiple mappings use the ing of intermediate table connections
Policy. The created intermediate table introduces the primary keys on both sides as foreign keys. Ejb3 provides configurable metadata for the intermediate table. You can
Use the table name and column name of the custom intermediate table.
Next we will take students and teachers as examples to introduce object bean development with many-to-many relationships.
Database tables to be mapped
Student
Field Name field type attribute description
Studentid (primary key) int (11) not null student ID
Studentname varchar (32) not null Student name
Teacher
Field Name field type attribute description
Teacherid (primary key) int (11) not null instructor ID
Teachername varchar (32) not null instructor name
Intermediate table teacher_student
Field Name field type attribute description
Student_id int (11) not null is
Foreign key
Teacher_id int (11) not null is
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
Foreign key
Student. Java
// Author: lihuoming
Package com. foshanshop. ejb3.bean;
Import java. Io. serializable;
Import java. util. hashset;
Import java. util. Set;
Import javax. Persistence. column;
Import javax. Persistence. entity;
Import javax. Persistence. generatedvalue;
Import javax. Persistence. ID;
Import javax. Persistence. manytoence;
Import javax. Persistence. Table;
@ Suppresswarnings ("serial ")
@ Entity
@ Table (name = "student ")
Public class student implements serializable {
Private integer studentid;
Private string studentname;
Private set <teacher> teachers = new hashset <teacher> ();
Public student (){}
Public student (string studentname ){
Studentname = studentname;
}
@ ID
@ Generatedvalue
Public integer getstudentid (){
Return studentid;
}
Public void setstudentid (integer studentid ){
This. studentid = studentid;
}
@ Column (nullable = false, length = 32)
Public String getstudentname (){
Return studentname;
}
Public void setstudentname (string studentname ){
Studentname = studentname;
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
}
@ Manytots (mappedby = "Students ")
Public set <teacher> getteachers (){
Return teachers;
}
Public void setteachers (set <teacher> teachers ){
This. Teachers = teachers;
}
}
@ Manytomany the comment indicates that student is one side of the many-to-many relationship. The mappedby attribute defines student as the maintenance end of the bidirectional relationship.
(Owning side ).
Teacher. Java
// Author: lihuoming
Package com. foshanshop. ejb3.bean;
Import java. Io. serializable;
Import java. util. hashset;
Import java. util. Set;
Import javax. Persistence. cascadetype;
Import javax. Persistence. column;
Import javax. Persistence. entity;
Import javax. Persistence. fetchtype;
Import javax. Persistence. generatedvalue;
Import javax. Persistence. ID;
Import javax. Persistence. joincolumn;
Import javax. Persistence. jointable;
Import javax. Persistence. manytoence;
Import javax. Persistence. Table;
@ Suppresswarnings ("serial ")
@ Entity
@ Table (name = "teacher ")
Public class teacher implements serializable {
Private integer teacherid;
Private string teachername;
Private set <student> students = new hashset <student> ();
Public Teacher (){}
Public Teacher (string teachername ){
Teachername = teachername;
}
@ ID
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
@ Generatedvalue
Public integer getteacherid (){
Return teacherid;
}
Public void setteacherid (integer teacherid ){
This. teacherid = teacherid;
}
@ Column (nullable = false, length = 32)
Public String getteachername (){
Return teachername;
}
Public void setteachername (string teachername ){
Teachername = teachername;
}
@ Manytomany (cascade = cascadetype. persist, fetch = fetchtype. Lazy)
@ Jointable (name = "teacher_student ",
Joincolumns = {@ joincolumn (name = "teacher_id", referencedcolumnname = "teacherid ")},
Inversejoincolumns = {@ joincolumn (name = "student_id", referencedcolumnname =
"Studentid ")})
Public set <student> getstudents (){
Return students;
}
Public void setstudents (set <student> students ){
This. Students = students;
}
Public void addstudent (Student ){
If (! This. Students. Contains (student )){
This. Students. Add (student );
}
}
Public void removestudent (Student ){
This. Students. Remove (student );
}
}
@ Manytomany the comment indicates that teacher is the end of the many-to-many relationship. @ Jointable describes the relationship between multiple-to-multiple data tables. Name
Specifies the name of the intermediate table. joincolumns defines the foreign key relationship between the intermediate table and the teacher table. In the above Code, the intermediate table teacher_student
The teacher_id column of is the foreign key column corresponding to the primary key column of the teacher table. The inversejoincolumns attribute defines the middle table and the other end (student)
.
To use the above Entity Bean, we define a session bean as its user. The following is the service interface of Session Bean.
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
Three business methods, insertteacher, getteacherbyid, and getstudentbyid, are defined. The business functions of the three methods are as follows:
Insertteacher adds a teacher (with students) to the database
Getteacherbyid: obtains the specified instructor ID.
Getstudentbyid
The following are the service interfaces and implementation classes of Session Bean.
Teacherdao. Java
// Author: lihuoming
Package com. foshanshop. ejb3;
Import com. foshanshop. ejb3.bean. student;
Import com. foshanshop. ejb3.bean. teacher;
Public interface teacherdao {
Public void insertteacher (string name, string [] studentnames );
Public Teacher getteacherbyid (integer teacherid );
Public student getstudentbyid (integer studentid );
}
Teacherdaobean. Java
// Author: lihuoming
Package com. foshanshop. ejb3.impl;
Import javax. EJB. Remote;
Import javax. EJB. stateless;
Import javax. Persistence. entitymanager;
Import javax. Persistence. persistencecontext;
Import com. foshanshop. ejb3.teacherdao;
Import com. foshanshop. ejb3.bean. student;
Import com. foshanshop. ejb3.bean. teacher;
@ Stateless
@ Remote ({teacherdao. Class })
Public class teacherdaobean implements teacherdao {
@ Persistencecontext
Protected entitymanager em;
Public void insertteacher (string name, string [] studentnames ){
Teacher = new teacher (name );
If (studentnames! = NULL ){
For (INT I = 0; I <studentnames. length; I ++ ){
Teacher. addstudent (new student (studentnames [I]);
}
}
Em. persist (teacher );
}
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
Public Teacher getteacherbyid (integer teacherid ){
Teacher = em. Find (teacher. Class, teacherid );
If (teacher! = NULL) teacher. getstudents (). Size ();
Return teacher;
}
Public student getstudentbyid (integer studentid ){
Student = em. Find (student. Class, studentid );
If (student! = NULL) student. getteachers (). Size ();
Return student;
}
}
The following is the JSP client code of Session Bean:
Manytomanytest. jsp
<% @ Page contenttype = "text/html; charset = GBK" %>
<% @ Page import = "com. foshanshop. ejb3.teacherdao,
Com. foshanshop. ejb3.bean .*,
Javax. Naming .*,
Java. util. * "%>
<%
Properties props = new properties ();
Props. setproperty ("Java. Naming. Factory. Initial ",
"Org. jnp. Interfaces. namingcontextfactory ");
Props. setproperty ("Java. Naming. provider. url", "localhost: 1099 ");
Props. setproperty ("Java. Naming. Factory. url. pkgs", "org. JBoss. Naming ");
Initialcontext CTX = new initialcontext (props );
Try {
Teacherdao = (teacherdao) CTX. Lookup ("teacherdaobean/remote ");
Teacherdao. insertteacher ("instructor Li", new string [] {"Zhang Xiaohong", "Zhu Xiaoguang", ""});
Teacher = teacherdao. getteacherbyid (New INTEGER (1 ));
If (teacher! = NULL ){
Out. println ("======= get the name of the instructor numbered 1:" + teacher. getteachername () +"
=======< Br> ");
Iterator = teacher. getstudents (). iterator ();
While (iterator. hasnext ()){
Student = (student) iterator. Next ();
Out. println ("& nbsp; his students:" + student. getstudentname () + "<br> ");
}
} Else {
Out. println ("no teacher with ID 1 found <br> ");
}
JBoss ejb3.0 instance tutorial
Copyright: Li fuming
Student = teacherdao. getstudentbyid (New INTEGER (1 ));
If (student! = NULL ){
Out. println ("======= get the name of a student numbered 1:" + student. getstudentname () +"
=======< Br> ");
Iterator = student. getteachers (). iterator ();
While (iterator. hasnext ()){
Teacher Tc = (teacher) iterator. Next ();
Out. println ("& nbsp; his teacher:" + TC. getteachername () + "<br> ");
}
} Else {
Out. println ("1 student not found <br> ");
}
} Catch (exception e ){
Out. println (E. getmessage ());
}
%>
The EJB source code in this example is in the manytomany folder (source code download: http://www.foshanshop.net/), the class library used in the project
In the Lib folder of the parent directory. To publish this example EJB (make sure that the environment variable jboss_home is configured and JBoss is started), you can execute
Ant's deploy task. The data source configuration file used in the example is a mysql-ds.xml that you can find in the downloaded file. Database Name
Foshanshop
The client code in this example is in the ejbtest folder. To publish a client application, You can execute the ant deploy task. Pass
Http: // localhost: 8080/ejbtest/manytomanytest. jsp to access the client.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.