EJB_開發單表映射的實體bean

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   color   

開發單表映射的實體bean

實體bean

它屬於java持久化規範(JPA)裡的技術,實體bean通過中繼資料在Javabean和資料庫表之間建立起映射關係,然後Java程式員就可以隨心所欲的使用物件導向的編程思想來操縱資料庫。 JPA的出現主要是為了簡化現有的持久化開發工作和整合ORM技術,目前實現的JPA規範的主流產品有Hibernate、TopLink和OpenJPA,在JBoss中採用了Hibernate 作為其持久化實現產品。

 

添加JPA的設定檔persistence.xml

根據JPA規範的要求:在實體bean應用中,我們需要項目根目錄下建立META-INF目錄加入持久化設定檔persistence.xml

 

步驟:

建立一個實體bean項目,建立JavaProject:EntityBean,添加EJBjar檔案,在項目根目錄下建立一個META-INF檔案夾→建立persistence.xml

<?xmlversion="1.0"?>

<persistencexmlns="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"

    version="1.0">

 

</persistence>

 

在persistence裡定義一個持久化單元,就是一堆實體類的集合。

    <persistence-unitname="hqu"transaction-type="JTA">

       <jta-data-source>java:hquDS</jta-data-source>

    </persistence-unit>

 

    <persistence-unitname="hqu"transaction-type="JTA">

       <jta-data-source>java:hquDS</jta-data-source>

       <properties>

       <!--測試階段下面Hibernate很有用-->

           <propertyname="hibernate.hbm2ddl.auto"value="update"/>

           <!--顯示最終執行的SQL-->

           <propertyname="hibernate.show_sql"value="true"/>

           <!--格式化顯示的SQL-->

           <propertyname="hibernate.format_sql"value="true"/>

       </properties>

    </persistence-unit>

 

開發實體bean:

在src下建立Person在cn.hqu.bean下,id,name,和getter,setter。序列化,重寫hashcode和equals。

 

和資料庫進行映射(資料庫hqutest要有一張叫person的表有id和name),採用註解

至少有一個主鍵@Id

package cn.hqu.bean;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "person")public class Person implements Serializable {private Integer id;private String name;@Id@Column(name = "id")@GeneratedValue(strategy = GenerationType.AUTO)public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(name="name",length=20,nullable=false)public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((id == null) ? 0 : id.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (id == null) {if (other.id != null)return false;} else if (!id.equals(other.id))return false;return true;}}

添加對實體bean進行增刪改查,

建立會話bean:

         1.建立介面PersonService在cn.hqu.service下

 

         public interface PersonService {

    public abstract void save(Person person);

    public abstract void update(Person person);

    public abstract void delete(Integer id);

    public abstractList<Person> getPersons();

}

 

2.定義介面的實作類別:

PersonServiceBean在cn.hqu.service.impl

package cn.hqu.service.impl;import java.util.List;import javax.ejb.Remote;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import cn.hqu.bean.Person;import cn.hqu.service.PersonService;@Stateless@Remote(PersonService.class)public class PersonServiceBean implements PersonService {@PersistenceContext EntityManager em;@Overridepublic void save(Person person) {//對建立狀態的實體進行儲存,在實體bean中有四種狀態://建立狀態,託管狀態,游離狀態,刪除狀態em.persist(person);}@Overridepublic void update(Person person) {//調用merge的前提是person已經處於游離狀態,在這個狀態的情況下,//對bean進行修改,才調用merge方法。//如果對象屬於託管狀態,我們直接調用person的save方法就可以進行修改了。em.merge(person);}@Overridepublic void delete(Integer id) {//刪除資料沒必要再查詢,使用getReference效能比較好,//getReference得到的是託管狀態的實體。em.remove(em.getReference(Person.class, id));}@SuppressWarnings("unchecked")@Overridepublic List<Person> getPersons() {return em.createQuery("select o from Person o").getResultList();}}

會話bean和實體bean都編製好了,接下來對應用進行打包發布。採用Ant

拷貝一份HelloWorld的Ant設定檔進行修改:

name換成EntityBean添加


執行打包工作,Ant,deploy。

 

發布:

因為這個持久化單元設定檔使用到了資料來源,所以在發布之前要確保發布了資料來源。

 

接下來可以編寫用戶端方法了,採用單元測試:

在介面右點擊建立單元測試,

 

拷貝一份HelloWorld的jndi.properties到項目src目錄下。

package junit.test;import static org.junit.Assert.fail;import java.util.List;import javax.naming.InitialContext;import org.junit.BeforeClass;import org.junit.Test;import cn.hqu.bean.Person;import cn.hqu.service.PersonService;public class PersonServiceTest {private static PersonService personService;@BeforeClasspublic static void setUpBeforeClass() throws Exception {try {InitialContext ctx = new InitialContext();personService = (PersonService) ctx.lookup("PersonServiceBean/remote");} catch (Exception e) {e.printStackTrace();}}@Testpublic void testSave() {personService.save(new Person("蘇志達"));}@Testpublic void testUpdate() {Person person = personService.getPerson(2);person.setName("xxx");personService.update(person);}@Testpublic void testDelete() {personService.delete(1);}@Testpublic void testGetPersons() {List<Person> personList = personService.getPersons();for (Person person : personList) {System.out.println(person.getName());}}@Testpublic void testGetPerson() {System.out.println(personService.getPerson(2).getName());}}

執行發布,deploy

 

問題:

運行ant的deploy,報錯,test問題,指定不編譯junit 27行

    <target name="compile" depends="prepare"description="編譯">

        <!--對源檔案進行編譯,destdir編譯後class存放目錄-->

        <javac srcdir="${src.dir}" destdir="${build.dir}" includes="cn/**">

            <!--編譯依賴的jar檔案-->

            <classpath refid="build.classpath"></classpath>

        </javac>

    </target>

 

產生亂碼,將資料庫修改為UTF-8,

或者修改


實體bean就開發就完了。

源碼:http://pan.baidu.com/s/1pJ7Eunx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.