1. Add a mysql-ds.xml in the jboss deployment Directory, which can be found in the jboss installation directory
MySqlDS
jdbc:mysql://127.0.0.1:3306/student
com.mysql.jdbc.Driver
root
123456
org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter
mySQL
2. Add JPA support in the EJB Project
This operation usually makes it OK for the program to help us establish it automatically, as shown below:
Note that the above java version is usually the same as the java_home version.
In this step, we need to create a data source in eclipse.
Next, we select hibernate as the jpa specification, and eclipse will automatically configure the jpa configuration file for us. After the configuration is complete, the file may be like this.
org.lxh.model.MUser
Unfortunately, an error occurs when you deploy the project to jboss. Because the jboss data source is configured but the jpa configuration file does not use the jboss data source, and the transaction processor is not configured, you can refer to the following configuration.
java:MySqlDS
org.lxh.model.MUser
The jta-data-source node is configured with the jboss data source's jndi, And the jpa transaction processor is configured in properties.
3. Create an object bean in the corresponding package.
Right-click the corresponding package and select create object bean. The object Bean can be created successfully as prompted.
package org.lxh.model;import java.io.Serializable;import javax.persistence.*;/** * The persistent class for the m_user database table. * */@Entity@Table(name="m_user")@NamedQuery(name="MUser.findAll", query="SELECT m FROM MUser m")public class MUser implements Serializable {private static final long serialVersionUID = 1L;@Idprivate int id;private String address;private String name;private String password;public MUser() {}public int getId() {return this.id;}public void setId(int id) {this.id = id;}public String getAddress() {return this.address;}public void setAddress(String address) {this.address = address;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public String getPassword() {return this.password;}public void setPassword(String password) {this.password = password;}}
4. Get EntityManager In the EJB service Bean
This is basically similar to the dependency injection principle. We can use @ ejb annotations to inject EJB, so the EntityManager injection is similar.
@ PersistenceContext (unitName = "TestTransaction") private EntityManager em; public void updateUser () throws Exception {MUser m = em. find (MUser. class, 3); m. setName ("Liu Xiaojun XX"); em. merge (m );}
The first two statements of code above implement EntityManager injection, which can be followed by related operations. What you need to understand is that the jpa database does not need to explicitly start the transaction commit transaction.