分享

如何把JDBC方式的代码修改JPA方式的代码 - 笔记 - 李绪成 - CSDN学生大本营...

 yanjj 2010-10-30
JDBC应用改成JPA程序,需要把原来通过JDBC API访问数据库的代码替换成使用JPA代码。
JDBC访问数据库的主要工作包括:
n得到JDBC驱动程序;
n使用DriverManagerConnectionStatementResultSet等;
而使用JPA完成数据的操作包括:
n得到JDBC驱动程序;
n得到持久性提供者相关类库和配置文件;
n提供实体类;
n使用PersistenceEntityManagerFactoryEntity等接口。
要完成修改,需要完成如下工作:
n提供配置文件persistence.xml文件和持久性提供者相关类库;
n需要把原来表示信息的普通JavaBean修改实体类;
nJDBC代码修改为JPA代码。
下面以图书添加为例介绍。
1、提供配置文件persistence.xml文件和持久性提供者相关类库
可以参考JP两个相关实验中的过程,添加JPA支持,可以为工程添加类库,并且会生成persistence.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java./xml/ns/persistence"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://java./xml/ns/persistence
    http://java./xml/ns/persistence/persistence_1_0.xsd" version="1.0">
   
    <persistence-unit name="bookstore_PU"
       transaction-type="RESOURCE_LOCAL">
       <provider>
           oracle.toplink.essentials.PersistenceProvider
       </provider>
       <class>beans.Book</class>
       <properties>
           <property name="toplink.jdbc.driver"
              value="com.mysql.jdbc.Driver" />
           <property name="toplink.jdbc.url"
              value="jdbc:mysql://localhost:3306/entitytest" />
           <property name="toplink.jdbc.user" value="root" />
           <property name="toplink.jdbc.password" value="root" />
       </properties>
    </persistence-unit>
</persistence>
2、把原来的JavaBean修改为实体类
可以使用MyEclipse中的功能,参考JPA的两个相关实验。
修改前JavaBean的代码如下:
package beans;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
publicclass Book implements java.io.Serializable {
 
     private String bid;
     private String bname;
     private Float price;
     private String author;
     private String press;
 
    public Book() {
    }
 
    public Book(String bid, String bname) {
        this.bid = bid;
        this.bname = bname;
    }
 
    public Book(String bid, String bname, Float price, String author, String press) {
        this.bid = bid;
        this.bname = bname;
        this.price = price;
        this.author = author;
        this.press = press;
    }
 
    public String getBid() {
        returnthis.bid;
    }
   
    publicvoid setBid(String bid) {
        this.bid = bid;
    }
 
    public String getBname() {
        returnthis.bname;
    }
   
    publicvoid setBname(String bname) {
        this.bname = bname;
    }
 
    public Float getPrice() {
        returnthis.price;
    }
   
    publicvoid setPrice(Float price) {
        this.price = price;
    }
 
    public String getAuthor() {
        returnthis.author;
    }
   
    publicvoid setAuthor(String author) {
        this.author = author;
    }
    public String getPress() {
        returnthis.press;
    }
    publicvoid setPress(String press) {
        this.press = press;
    }
}
修改的内容包括:
n在类上使用@Entity声明Bean类为实体类;
n在类上使用@Table声明与数据库中表的对应关系;
n在主键属性上(或者get方法上)使用@Id标注主键属性;
n在属性上使用@Column标注属性与表中列的对应关系;
修改后JavaBean的代码如下:
package beans;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
 
/**
 *Bookentity.@authorMyEclipsePersistenceTools
 */
@Entity
@Table(name="book"
    ,catalog="entitytest"
)
 
publicclass Book implements java.io.Serializable {
 
 
    // Fields   
 
     private String bid;
     private String bname;
     private Float price;
     private String author;
     private String press;
 
 
    // Constructors
 
    /**defaultconstructor*/
    public Book() {
    }
 
    /**minimalconstructor*/
    public Book(String bid, String bname) {
        this.bid = bid;
        this.bname = bname;
    }
   
    /**fullconstructor*/
    public Book(String bid, String bname, Float price, String author, String press) {
        this.bid = bid;
        this.bname = bname;
        this.price = price;
        this.author = author;
        this.press = press;
    }
 
  
    // Property accessors
    @Id
   
    @Column(name="BID", unique=true, nullable=false, length=13)
 
    public String getBid() {
        returnthis.bid;
    }
   
    publicvoid setBid(String bid) {
        this.bid = bid;
    }
   
    @Column(name="BNAME", nullable=false, length=30)
 
    public String getBname() {
        returnthis.bname;
    }
   
    publicvoid setBname(String bname) {
        this.bname = bname;
    }
   
    @Column(name="PRICE", precision=12, scale=0)
 
    public Float getPrice() {
        returnthis.price;
    }
   
    publicvoid setPrice(Float price) {
        this.price = price;
    }
   
    @Column(name="AUTHOR", length=30)
 
    public String getAuthor() {
        returnthis.author;
    }
   
    publicvoid setAuthor(String author) {
        this.author = author;
    }
   
    @Column(name="PRESS", length=30)
 
    public String getPress() {
        returnthis.press;
    }
   
    publicvoid setPress(String press) {
        this.press = press;
    }
}
3、访问代码修改如下
修改前的代码:
    // 使用JDBC
    publicvoid addBook(String bookid, String bookname, String author,float price,String press) {
      
       Connection con = null;
       PreparedStatement stmt = null;
       try {
           // 指出连接数据库所需要的驱动程序
           Class.forName("oracle.jdbc.driver.OracleDriver");
 
           // 建立与数据库之间的连接
           con = DriverManager.getConnection(
                  "jdbc:oracle:thin:@myserver:1521:mydb", "scott", "tiger");
 
           // 编写查询数据库信息的SQL语句
           String sql = "insert into book values(?,?,?,?,?)";
 
           // 创建语句对象,用于执行SQL语句
           stmt = con.prepareStatement(sql);
           stmt.setString(1, bookid);
           stmt.setString(2, bookname);
           stmt.setFloat(3, price);
           stmt.setString(4, author);
           stmt.setString(5, press);
 
           // 执行SQL语句得到结果集
           stmt.executeUpdate();
 
       } catch (Exception e) {
           System.out.println(e.getMessage());
       } finally {
           // 关闭相关对象
           if (stmt != null)
              try {
                  stmt.close();
              } catch (Exception ee) {
              }
           if (con != null)
              try {
                  con.close();
              } catch (Exception ee) {
              }
       }
    }
修改后的代码:
    // 使用JPA
    publicvoid addBookJPA(String bookid, String bookname, String author,float price,String press) {
       // 创建图书对象
       Book book = new Book();
       book.setBid(bookid);
       book.setBname(bookname);
       book.setAuthor(author);
       book.setPress(press);
       book.setPrice(price);
      
       // 使用JPA完成操作
       EntityManagerFactory emf = Persistence.createEntityManagerFactory("bookstore_PU"); 
       EntityManager em = emf.createEntityManager();
       em.getTransaction().begin();
       em.persist(book);
       em.getTransaction().commit();
       em.close();
       emf.close();
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多