您的位置:首页 > 编程语言 > Java开发

Myeclipse结合mysql和Jboss的EJB实体bean实例

2008-05-02 17:57 483 查看
 

演示地址:

http://d.download.csdn.net/fd3/aHR0cDovL2RsMi5jc2RuLm5ldC9kb3duMS8yMDA4MDUwMi8wMjE2MzA1MDQwNC5yYXI=!438865

说明:  分两部分,由于第一部分的演示有部分大家看了会不明白的,在第二部分进行了补充。

 

 


import java.util.Properties;




import javax.naming.InitialContext;


import javax.naming.NamingException;




import com.SelectCourse;


import com.SelectCourseFacadeRemote;








public class Test ...{






    /**//**


     * @param args


     */




    public static void main(String[] args) ...{


        Properties props = new Properties();


        props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");


        props.setProperty("java.naming.provider.url", "localhost:1099");


        props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");




        InitialContext ctx;




        try ...{


            ctx = new InitialContext(props);


            SelectCourseFacadeRemote remote = (SelectCourseFacadeRemote) ctx.lookup("SelectCourseFacade/remote");


            SelectCourse sc = new SelectCourse();


            sc.setId((long)500);


            sc.setCourseId(52);


            sc.setStuId(533);


            


            remote.save(sc);


            ctx.close();


            




        } catch (NamingException e) ...{


            System.out.println(e.getMessage());




        } finally ...{




        }


    }




}



 

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="myEjbEntityBean" transaction-type="JTA">


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


    </persistence-unit>


  


</persistence>



 

 


package com;




import javax.persistence.Column;


import javax.persistence.Entity;


import javax.persistence.Id;


import javax.persistence.Table;






/**//**


 * SelectCourse entity.


 * 


 * @author MyEclipse Persistence Tools


 */


@Entity




@Table(name = "select_course", catalog = "test", uniqueConstraints = ...{})




public class SelectCourse implements java.io.Serializable ...{




    // Fields




    private Long id;


    private Integer stuId;


    private Integer courseId;




    // Constructors






    /**//** default constructor */




    public SelectCourse() ...{


    }






    /**//** minimal constructor */




    public SelectCourse(Long id) ...{


        this.id = id;


    }






    /**//** full constructor */




    public SelectCourse(Long id, Integer stuId, Integer courseId) ...{


        this.id = id;


        this.stuId = stuId;


        this.courseId = courseId;


    }




    // Property accessors


    @Id


    @Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = true)




    public Long getId() ...{


        return this.id;


    }






    public void setId(Long id) ...{


        this.id = id;


    }




    @Column(name = "stuId", unique = false, nullable = true, insertable = true, updatable = true)




    public Integer getStuId() ...{


        return this.stuId;


    }






    public void setStuId(Integer stuId) ...{


        this.stuId = stuId;


    }




    @Column(name = "courseId", unique = false, nullable = true, insertable = true, updatable = true)




    public Integer getCourseId() ...{


        return this.courseId;


    }






    public void setCourseId(Integer courseId) ...{


        this.courseId = courseId;


    }




}

 


package com;




import java.util.List;


import javax.ejb.Remote;






/**//**


 * Remote interface for SelectCourseFacade.


 * 


 * @author MyEclipse Persistence Tools


 */


@Remote




public interface SelectCourseFacadeRemote ...{




    /**//**


     * Perform an initial save of a previously unsaved SelectCourse entity. All


     * subsequent persist actions of this entity should use the #update()


     * method.


     * 


     * @param entity


     *            SelectCourse entity to persist


     * @throws RuntimeException


     *             when the operation fails


     */


    public void save(SelectCourse entity);






    /**//**


     * Delete a persistent SelectCourse entity.


     * 


     * @param entity


     *            SelectCourse entity to delete


     * @throws RuntimeException


     *             when the operation fails


     */


    public void delete(SelectCourse entity);






    /**//**


     * Persist a previously saved SelectCourse entity and return it or a copy of


     * it to the sender. A copy of the SelectCourse entity parameter is returned


     * when the JPA persistence mechanism has not previously been tracking the


     * updated entity.


     * 


     * @param entity


     *            SelectCourse entity to update


     * @returns SelectCourse the persisted SelectCourse entity instance, may not


     *          be the same


     * @throws RuntimeException


     *             if the operation fails


     */


    public SelectCourse update(SelectCourse entity);




    public SelectCourse findById(Long id);






    /**//**


     * Find all SelectCourse entities with a specific property value.


     * 


     * @param propertyName


     *            the name of the SelectCourse property to query


     * @param value


     *            the property value to match


     * @param rowStartIdxAndCount


     *            Optional int varargs. rowStartIdxAndCount[0] specifies the the


     *            row index in the query result-set to begin collecting the


     *            results. rowStartIdxAndCount[1] specifies the the maximum


     *            count of results to return.


     * @return List<SelectCourse> found by query


     */


    public List<SelectCourse> findByProperty(String propertyName, Object value,


            int... rowStartIdxAndCount);




    public List<SelectCourse> findByStuId(Object stuId,


            int... rowStartIdxAndCount);




    public List<SelectCourse> findByCourseId(Object courseId,


            int... rowStartIdxAndCount);






    /**//**


     * Find all SelectCourse entities.


     * 


     * @param rowStartIdxAndCount


     *            Optional int varargs. rowStartIdxAndCount[0] specifies the the


     *            row index in the query result-set to begin collecting the


     *            results. rowStartIdxAndCount[1] specifies the the maximum


     *            count of results to return.


     * @return List<SelectCourse> all SelectCourse entities


     */


    public List<SelectCourse> findAll(int... rowStartIdxAndCount);


}

 

 


package com;




import java.util.List;


import java.util.logging.Level;


import javax.ejb.Stateless;


import javax.persistence.EntityManager;


import javax.persistence.PersistenceContext;


import javax.persistence.Query;






/**//**


 * Facade for entity SelectCourse.


 * 


 * @see com.SelectCourse


 * @author MyEclipse Persistence Tools


 */


@Stateless


public class SelectCourseFacade implements SelectCourseFacadeLocal,




        SelectCourseFacadeRemote ...{


    // property constants


    public static final String STU_ID = "stuId";


    public static final String COURSE_ID = "courseId";




    @PersistenceContext


    private EntityManager entityManager;






    /**//**


     * Perform an initial save of a previously unsaved SelectCourse entity. All


     * subsequent persist actions of this entity should use the #update()


     * method.


     * 


     * @param entity


     *            SelectCourse entity to persist


     * @throws RuntimeException


     *             when the operation fails


     */




    public void save(SelectCourse entity) ...{


        LogUtil.log("saving SelectCourse instance", Level.INFO, null);




        try ...{


            entityManager.persist(entity);


            LogUtil.log("save successful", Level.INFO, null);




        } catch (RuntimeException re) ...{


            LogUtil.log("save failed", Level.SEVERE, re);


            throw re;


        }


    }






    /**//**


     * Delete a persistent SelectCourse entity.


     * 


     * @param entity


     *            SelectCourse entity to delete


     * @throws RuntimeException


     *             when the operation fails


     */




    public void delete(SelectCourse entity) ...{


        LogUtil.log("deleting SelectCourse instance", Level.INFO, null);




        try ...{


            entity = entityManager.getReference(SelectCourse.class, entity


                    .getId());


            entityManager.remove(entity);


            LogUtil.log("delete successful", Level.INFO, null);




        } catch (RuntimeException re) ...{


            LogUtil.log("delete failed", Level.SEVERE, re);


            throw re;


        }


    }






    /**//**


     * Persist a previously saved SelectCourse entity and return it or a copy of


     * it to the sender. A copy of the SelectCourse entity parameter is returned


     * when the JPA persistence mechanism has not previously been tracking the


     * updated entity.


     * 


     * @param entity


     *            SelectCourse entity to update


     * @returns SelectCourse the persisted SelectCourse entity instance, may not


     *          be the same


     * @throws RuntimeException


     *             if the operation fails


     */




    public SelectCourse update(SelectCourse entity) ...{


        LogUtil.log("updating SelectCourse instance", Level.INFO, null);




        try ...{


            SelectCourse result = entityManager.merge(entity);


            LogUtil.log("update successful", Level.INFO, null);


            return result;




        } catch (RuntimeException re) ...{


            LogUtil.log("update failed", Level.SEVERE, re);


            throw re;


        }


    }






    public SelectCourse findById(Long id) ...{


        LogUtil.log("finding SelectCourse instance with id: " + id, Level.INFO,


                null);




        try ...{


            SelectCourse instance = entityManager.find(SelectCourse.class, id);


            return instance;




        } catch (RuntimeException re) ...{


            LogUtil.log("find failed", Level.SEVERE, re);


            throw re;


        }


    }






    /**//**


     * Find all SelectCourse entities with a specific property value.


     * 


     * @param propertyName


     *            the name of the SelectCourse property to query


     * @param value


     *            the property value to match


     * @param rowStartIdxAndCount


     *            Optional int varargs. rowStartIdxAndCount[0] specifies the the


     *            row index in the query result-set to begin collecting the


     *            results. rowStartIdxAndCount[1] specifies the the maximum


     *            number of results to return.


     * @return List<SelectCourse> found by query


     */


    @SuppressWarnings("unchecked")


    public List<SelectCourse> findByProperty(String propertyName,




            final Object value, final int... rowStartIdxAndCount) ...{


        LogUtil.log("finding SelectCourse instance with property: "


                + propertyName + ", value: " + value, Level.INFO, null);




        try ...{


            final String queryString = "select model from SelectCourse model where model."


                    + propertyName + "= :propertyValue";


            Query query = entityManager.createQuery(queryString);


            query.setParameter("propertyValue", value);




            if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) ...{


                int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);




                if (rowStartIdx > 0) ...{


                    query.setFirstResult(rowStartIdx);


                }






                if (rowStartIdxAndCount.length > 1) ...{


                    int rowCount = Math.max(0, rowStartIdxAndCount[1]);




                    if (rowCount > 0) ...{


                        query.setMaxResults(rowCount);


                    }


                }


            }


            return query.getResultList();




        } catch (RuntimeException re) ...{


            LogUtil.log("find by property name failed", Level.SEVERE, re);


            throw re;


        }


    }




    public List<SelectCourse> findByStuId(Object stuId,




            int... rowStartIdxAndCount) ...{


        return findByProperty(STU_ID, stuId, rowStartIdxAndCount);


    }




    public List<SelectCourse> findByCourseId(Object courseId,




            int... rowStartIdxAndCount) ...{


        return findByProperty(COURSE_ID, courseId, rowStartIdxAndCount);


    }






    /**//**


     * Find all SelectCourse entities.


     * 


     * @param rowStartIdxAndCount


     *            Optional int varargs. rowStartIdxAndCount[0] specifies the the


     *            row index in the query result-set to begin collecting the


     *            results. rowStartIdxAndCount[1] specifies the the maximum


     *            count of results to return.


     * @return List<SelectCourse> all SelectCourse entities


     */


    @SuppressWarnings("unchecked")




    public List<SelectCourse> findAll(final int... rowStartIdxAndCount) ...{


        LogUtil.log("finding all SelectCourse instances", Level.INFO, null);




        try ...{


            final String queryString = "select model from SelectCourse model";


            Query query = entityManager.createQuery(queryString);




            if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) ...{


                int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);




                if (rowStartIdx > 0) ...{


                    query.setFirstResult(rowStartIdx);


                }






                if (rowStartIdxAndCount.length > 1) ...{


                    int rowCount = Math.max(0, rowStartIdxAndCount[1]);




                    if (rowCount > 0) ...{


                        query.setMaxResults(rowCount);


                    }


                }


            }


            return query.getResultList();




        } catch (RuntimeException re) ...{


            LogUtil.log("find all failed", Level.SEVERE, re);


            throw re;


        }


    }




}

 

mysql-ds.xml

 


<?xml version="1.0" encoding="UTF-8"?>


<datasources>


<local-tx-datasource>


<jndi-name>DefaultMySqlDS</jndi-name>


<connection-url>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK


</connection-url>


<driver-class>org.gjt.mm.mysql.Driver</driver-class>


<user-name>root</user-name>


<password>admin</password>


<metadata>


<type-mapping>mySQL</type-mapping>


</metadata>


</local-tx-datasource>


</datasources>

 

测试通过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息