Database manipulation Technology (JPA) in EJB

Source: Internet
Author: User
Tags dname jboss

I. INTRODUCTION----WHAT is JPA
The Java persistence API, which specifies that the mapping of objects to data tables is described using annotations or XML,
Implements persisting object information to a database. Currently, the HIBERNATE\TOPLINK\OPENJPA framework supports the JPA specification.
In this example, we demonstrate the realization of the employee-department many-to-one relationship through JPA technology.

Ii. JPA Development process
Pre-set up an EJB project
A. Configure the data source DataSource, modify the *-ds.xml file, and put it in the server's deploy directory
Tip: Specify the connection database with that data source in the configuration file:
The value of the jndi-name that encapsulates the data source in Mysql-ds.xml (such as jmysqlds) must correspond to Jta-data-source in Persistence.xml (Java:mysqlds).
B. Create a project, create a persistence.xml file under Src/meta-inf, reference Java:datasource name
Tip: Specify persistence in the configuration file with that persistence unit (can have multiple):
<persistence-unit name= "Mysqlpu" > in persistence.xml must correspond to the annotation @PersistenceContext (daoimpl "unitname=") in Mysqlpu .
C. Write Entitybean, implement serialization, Setter/getter method, Equals/hashcode method
D. Using annotations to describe mapping information with data
E. Writing Sessionbean DAO component Manipulation Entitybean
F. Implementing Crup Operations using Entitymanager objects in Sessionbean

Iii. core configuration files and code
Mysql-ds.xml-----persistence.xml-------Entity Bean (EMP Employee Class +dept departmental Class)------session Bean (interface + time Class)------test class

3.1 Mysql-ds.xml
Configure data sources, including URLs, passwords, user names, etc.
<?xml version= "1.0" encoding= "UTF-8"?>
<!--See Http://www.jboss.org/community/wiki/Multiple1PC For information about Local-tx-datasource--
<!--$Id: mysql-ds.xml 88948 2009-05-15 14:09:08z Jesper.pedersen $--
<!--Datasource config for MySQL using 3.0.9 available from:
Http://www.mysql.com/downloads/api-jdbc-stable.html
-
<datasources>
<local-tx-datasource>
<jndi-name>MySqlDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/ejb</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password>sd100301</password>
<max-pool-size>20</max-pool-size>
<min-pool-size>1</min-pool-size>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.mysqlexceptionsorter</ Exception-sorter-class-name>
<!--should only being used on drivers after 3.22.1 with ' ping ' support
<valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.mysqlvalidconnectionchecker </valid-connection-checker-class-name>
-
<!--SQL to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-
<!--SQL to existing pooled connection when it's obtained from Pool-mysqlvalidconnectionchecker is prefer Red for newer drivers
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-
<!--corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional)--
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>

3.2 Persistence.xml
EJB configuration file, specifying the data source to use and configuring hibernate appropriate information
<?xml version= "1.0" encoding= "UTF-8"?>
<persistence version= "1.0"
Xmlns= "Http://java.sun.com/xml/ns/persistence"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/persistence
Http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd ">
<persistence-unit name= "Mysqlunit" transaction-type= "JTA" >
<jta-data-source>java:MySqlDS</jta-data-source>
<properties>
<property name= "Hibernate.hbm2ddl.auto" value= "Update"/>
<property name= "Hibernate.show_sql" value= "true"/>
<property name= "Hibernate.format_sql" value= "true"/>
</properties>
</persistence-unit>
</persistence>

3.3 Entity Bean
Employee Class EMP
Specifies that this is an entity class, the corresponding table name, the ID, and the name of the column that corresponds to each property.
@Entity
@Table (name = "EMP")
public class Emp implements Serializable {
@Id
@GeneratedValue
@Column (name = "id")
private int id;
@Column (name= "ename", Length=20,nullable=false)
Private String ename;
@ManyToOne ()
@JoinColumn (name= "dept_id")
Private Dept Dept;
Public Emp () {
}

public Emp (int id, String ename) {
Super ();
This.id = ID;
This.ename = ename;
}
-------Add the Getter&setter method for each property here-----

Department category EMP
Specifies that this is an entity class, the corresponding table name, the ID, and the name of the column that corresponds to each property.
@Entity
@Table (name= "dept")
public class Dept implements Serializable {
@Id
@GeneratedValue
@Column (name= "id")
private int id;
@Column (name= "Dname", nullable=false,length=20)
Private String dname;
@OneToMany (mappedby= "dept")
Private set<emp> emps=new hashset<emp> ();
Public Dept () {
}
Public Dept (String dname) {
Super ();
This.dname = dname;
}
-------Add the Getter&setter method for each property here-----

3.4 Session bean (Implementation class for DAO interface +dao interface)
DAO interface
Import java.util.List;
Public interface Deptdao {
public void Add (Dept Dept);
Public Dept FindByID (int id);
Public List findAll ();
Public List showall ();
}

Implementation classes for DAO interfaces
Specifies that this is a session-free Sessionbean,
@Stateless
Declares that the Sessionbean remote service interface is Deptdao
@Remote (Deptdao.class)
public class Deptdaoimpl implements Deptdao {
Specifies the persistence unit used by the Entitymanager
@PersistenceContext (unitname= "Mysqlpu")
Entitymanager encapsulates various database operation methods such as Add, find, update, and so on.
Private Entitymanager em;
public void Add (Dept Dept) {
Em.persist (dept);
}
Public List FindAll () {
String jpql= "Select D from Dept D";
Return Em.createquery (JPQL). Getresultlist ();
}
Public Dept FindByID (int id) {
Dept Dept=em.find (dept.class, id);
return dept;
}
Public List ShowAll () {
String jpql= "Select D.id,d.dname,count (E)" +
"From Dept D left join D.emps e";
Return Em.createquery (JPQL). Getresultlist ();
}
}

3.5 Calling the class
Used to invoke Sessionbean in the EJB to implement database operations
Import java.util.*;
Import Java.util.Set;
Import javax.naming.*;
Import jpa.*;
public class Testdeptdao {
public static void Main (string[] args) throws Exception {
Testsave ();
}
public static void Testsave () throws Exception {
Blackbody part: Set the environment parameter first, then use the environment parameter to construct an object of the context.
The code is basically fixed. is required in all kinds of calls.
Hashtable env = new Hashtable ();
Env.put (Context.initial_context_factory,
"Org.jnp.interfaces.NamingContextFactory");
Env.put (Context.provider_url, "jnp://localhost:1099");
InitialContext context = new InitialContext (env);
Get the object of the implementation class through the context lookup method
Deptdao Deptdao = (Deptdao) context.lookup ("Deptdaoimpl/remote");
New Department of resumes--New employees collection--New employees--Set up relationships--Save new parts (this should cascade to save all new employee information)
Dept Dept = new Dept ();
Dept.setdname ("Sale");
set<emp> emps = new hashset<emp> ();
EMP EMP1 = new EMP ();
Emp1.setename ("Liang");
Emp1.setdept (dept);
Emps.add (EMP1);
EMP EMP2 = new EMP ();
Emp2.setename ("Xiao Wang");
Emp2.setdept (dept);
Emps.add (EMP2);
EMP Emp3 = new EMP ();
Emp3.setename ("Xiao Hua");
Emp3.setdept (dept);
Emps.add (Emp3);
Dept.setemps (Emps);
Deptdao.add (dept);
}
}

Database manipulation Technology (JPA) in EJB

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.