Myeclipse6.0实现JPA 创建

1.首先先创建一个JAVA项目,之后对其添入JPA(项目-->右键-->MyEclipse->Add JPA 功能) ;

2.一般JPA对Toplink的支持比对hibernate的支持好点,所以我们直接默认就好,-->next;

3.选择JPA配置的数据源,(Driver 、catalog\Schema..) -->Finish ;

4.选中其中的一个表,右键-->创建JPA 反向工程 ;(我创建了一个表MyUser里面有字段:id pk,name varchar(20),password varchar(20) 。)

5.先设置放置的路径,我放在一个jpaDaoTest包中,产生一个实体Bean并更改persistence.xml产生一个实体。persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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" version="1.0">
    
    <persistence-unit name="jpaTestPU"
        transaction-type="RESOURCE_LOCAL">
        <provider>
            oracle.toplink.essentials.PersistenceProvider
        </provider>
        <class>jpaDao.MyUser</class>
        <class>jpaDaoTest.EisArea</class>
        <properties>
            <property name="toplink.jdbc.driver"
                value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
            <property name="toplink.jdbc.url"
                value="jdbc:microsoft:sqlserver://210.51.168.147:1433;DatabaseName=www_souvi_com" />
            <property name="toplink.jdbc.user" value="web1621510" />
            <property name="toplink.jdbc.password" value="fhq2020" />
        </properties>
    </persistence-unit>

</persistence>

之后在勾选上 Java Data Access Generation创建接口和其实现方法。类型为Basic DAO默认即可。

6.Finish ;

MyUser.java

package jpaDao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;

/** *//**
* MyUser generated by MyEclipse Persistence Tools
*/
@Entity 
@Table(catalog = "web1621510",schema = "www_souvi_com",name = "MyUser",uniqueConstraints = ...{})
public class MyUser implements java.io.Serializable ...{

    // Fields

    private Integer id;
    private String name;
    private String password;

    // Constructors

    /** *//** default constructor */
    public MyUser() ...{
    }

    /** *//** minimal constructor */
    public MyUser(Integer id) ...{
        this.id = id;
    }

    /** *//** full constructor */
    public MyUser(Integer id, String name, String password) ...{
        this.id = id;
        this.name = name; 
        this.password = password;
    }

    // Property accessors
    @Id
    @Column(name = "id", unique = true, nullable = false, insertable = true, updatable = true)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Integer getId() ...{
        return this.id;
    }

    public void setId(Integer id) ...{
        this.id = id;
    }

    @Column(name = "name", unique = false, nullable = true, insertable = true, updatable = true, length = 20)
    public String getName() ...{
        return this.name;
    }

    public void setName(String name) ...{
        this.name = name;
    }

    @Column(name = "password", unique = false, nullable = true, insertable = true, updatable = true, length = 20)
    public String getPassword() ...{
        return this.password;
    }

    public void setPassword(String password) ...{
        this.password = password;
    }

}
IMyUserDAO.java

package jpaDao;

import java.util.List;

/** *//**
* Interface for MyUserDAO.

* @author MyEclipse Persistence Tools
*/

public interface IMyUserDAO ...{
    public void save(MyUser transientInstance);

    public void delete(MyUser persistentInstance);

    public MyUser update(MyUser detachedInstance);

    public MyUser findById(Integer id);

    public List<MyUser> findByProperty(String propertyName, Object value);

    public List<MyUser> findByName(Object name);

    public List<MyUser> findByPassword(Object password);

    public List<MyUser> findAll();
}
MyUserDAO.java

package jpaDao;

import java.util.List;
import java.util.logging.Level;
import javax.persistence.EntityManager;

/** *//**
* Data access object (DAO) for domain model class MyUser.

* @see jpaDao.MyUser
* @author MyEclipse Persistence Tools
*/

public class MyUserDAO implements IMyUserDAO ...{
    // property constants
    public static final String NAME = "name";
    public static final String PASSWORD = "password";

    private EntityManager getEntityManager() ...{
        return EntityManagerHelper.getEntityManager();
    }

    public void save(MyUser transientInstance) ...{
        EntityManagerHelper.log("saving MyUser instance", Level.INFO, null);
        try ...{
            getEntityManager().persist(transientInstance);
            EntityManagerHelper.log("save successful", Level.INFO, null);
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("save failed", Level.SEVERE, re);
            throw re;
        }
    }

    public void delete(MyUser persistentInstance) ...{
        EntityManagerHelper.log("deleting MyUser instance", Level.INFO, null);
        try ...{
            getEntityManager().remove(persistentInstance);
            EntityManagerHelper.log("delete successful", Level.INFO, null);
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("delete failed", Level.SEVERE, re);
            throw re;
        }
    }

    public MyUser update(MyUser detachedInstance) ...{
        EntityManagerHelper.log("updating MyUser instance", Level.INFO, null);
        try ...{
            MyUser result = getEntityManager().merge(detachedInstance);
            EntityManagerHelper.log("update successful", Level.INFO, null);
            return result;
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("update failed", Level.SEVERE, re);
            throw re;
        }
    }

    public MyUser findById(Integer id) ...{
        EntityManagerHelper.log("finding MyUser instance with id: " + id,
                Level.INFO, null);
        try ...{
            MyUser instance = getEntityManager().find(MyUser.class, id);
            return instance;
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("find failed", Level.SEVERE, re);
            throw re;
        }
    }

    @SuppressWarnings("unchecked")
    public List<MyUser> findByProperty(String propertyName, Object value) ...{
        EntityManagerHelper.log("finding MyUser instance with property: "
                + propertyName + ", value: " + value, Level.INFO, null);
        try ...{
            String queryString = "select model from MyUser model where model."
                    + propertyName + "= :propertyValue";
            return getEntityManager().createQuery(queryString).setParameter(
                    "propertyValue", value).getResultList();
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("find by property name failed",
                    Level.SEVERE, re);
            ;
            throw re;
        }
    }

    public List<MyUser> findByName(Object name) ...{
        return findByProperty(NAME, name);
    }

    public List<MyUser> findByPassword(Object password) ...{
        return findByProperty(PASSWORD, password);
    }

    @SuppressWarnings("unchecked")
    public List<MyUser> findAll() ...{
        EntityManagerHelper.log("finding all MyUser instances", Level.INFO,
                null);
        try ...{
            String queryString = "select model from MyUser model";
            return getEntityManager().createQuery(queryString).getResultList();
        } catch (RuntimeException re) ...{
            EntityManagerHelper.log("find all failed", Level.SEVERE, re);
            ;
            throw re;
        }
    }

}
现在我们写一个测试类吧,

import jpaDao.* ;
import java.util.*;
public class Test ...{

    /** *//**
     * @param args
     */
    public static void main(String[] args) ...{        
        // 开始事务
        EntityManagerHelper.beginTransaction();
        // 创建DAO
        MyUserDAO dao = new MyUserDAO();
        // 创建对象
        MyUser user = new MyUser() ;
        user.setName("chenhao") ;
        user.setPassword("password");
        //保存对象
        dao.save(user) ;
        //事务提交
        EntityManagerHelper.commit() ;
        System.out.println("++++++++++++++++++++++++");
        // 得到所有的数据并遍利
        List<MyUser> result = dao.findAll() ;
        for(MyUser o : result)...{
            System.out.println("id = " + o.getId()) ;
            System.out.println("name = " + o.getName()) ;
            System.out.println("password = " + o.getPassword()) ;
        }
    }

}

console:

[TopLink Info]: 2008.04.01 12:26:29.484--ServerSession(26680060)--TopLink, version: Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))
[TopLink Info]: 2008.04.01 12:27:08.437--ServerSession(26680060)--file:/D:/workspace/jpaTest/bin/-jpaTestPU login successful
2008-4-1 0:27:08 jpaDao.EntityManagerHelper log
信息: saving MyUser instance
2008-4-1 0:27:08 jpaDao.EntityManagerHelper log
信息: save successful
++++++++++++++++++++++++
2008-4-1 0:27:08 jpaDao.EntityManagerHelper log
信息: finding all MyUser instances
id = 1
name = chenhao

原文链接:http://hi.baidu.com/xfpsh/item/f393d3e54b6913098c3ea8c4

你可能感兴趣的:(MyEclipse,创建JPA)