原创,转载请标明源 http://asyty.iteye.com/blog/1249495
随便贴个入门示例,贴贴代码说明一下,个人觉得网上的例子都稍显简洁,虽然我这个也不复杂,
建议搜索网上其他简单例子互相配合参考下。例如 http://blog.chinaunix.net/space.php?uid=20426042&do=blog&id=1681669
1 eclipse新建ejb项目
File --> new Project --> EJB Project
数据库中建两张表 t_users, t_roles,即用户表和权限表,字段和entity bean(entitybean在后面)里定义要一致
在src-->META-INF文件夹下新建mysql-ds.xml,配置数据库连接
<datasources> <local-tx-datasource> <jndi-name>ejbDatasource</jndi-name> <connection-url> jdbc:mysql://localhost:3306/test </connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>root</user-name> <password></password> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter </exception-sorter-class-name> <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker </valid-connection-checker-class-name> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> </datasources>
新建persistence.xml,使用Hibernate的持久化单元,也就是要需要持久化的内容,即通过JNDI指定上面定义的数据库,可以配置多个持久化单元
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" 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_2_0.xsd"> <persistence-unit name="test"> <jta-data-source>java:/ejbDatasource</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> </properties> </persistence-unit> </persistence>
定义entity bean,主要是观察定义表对应的字段的annotation @id @GeneratedValue @NotNull @Colum @ManyToOne等等
Role.java
@Entity @Table(name = "T_ROLES") public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) //mysql支持自增ID,uuid等类型的id private Integer id; @NotNull @Column(name = "ROLE_NAME", length= 10) private String roleName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
Subscriber.java
@Entity @Table(name = "T_USERS") public class Subscriber implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "UUID", length = 36) private String uuid = UUID.randomUUID().toString(); @NotNull @Length(min = 2, max = 32) @Column(name = "user_name", unique = true) //uuid private String userName; @NotNull @Length(min = 6, max = 32) @Column(name = "user_password") private String password; @Column(name = "user_email", length = 50) private String email; @Column(name = "user_reg_time") @Temporal(value =TemporalType.TIMESTAMP) private Date regTime = new Date(); @NotNull @ManyToOne(targetEntity=Role.class) //默认lazy=false 也就是Role会被同时取出 @JoinColumn(name="role_id", referencedColumnName="id") private Role role; public Subscriber() { super(); } public String getUuid() { return uuid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setRole(Role role) { this.role = role; } public Role getRole() { return role; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public void setRegTime(Date regTime) { this.regTime = regTime; } public Date getRegTime() { return regTime; } }
这样,entity bean和数据库连接就定义好了
<---------------以下部分是 session bean-------------->
如果使用DAO访问数据库的话,就可以定义dao,service和action,本例中直接继承Dao模板,Dao模板中已定义增删改查等功能,可google下DAO模板。DAO,service相当于session bean,这里只写一下User的部分,role部分类似
SubscriberDao.java
@Local //@local @remote,表示这个ejb是远程调用还是本地调用 public interface SubscriberDao extends DAO<Subscriber>{ /** * 确定是否可以登录 */ public boolean checkUser(String username, String password); }
SubscriberDaoImpl.java
@Stateless public class SubscriberDaoImpl extends DaoSupport<Subscriber> implements SubscriberDao { @Override public boolean checkUser(String username, String password) { long count = (Long)getEntityManager().createQuery("select count(o) from SysUser o where o.userName=?1 and o.password=?2") .setParameter(1, username).setParameter(2, password).getSingleResult(); return count>0; } }
@Local public interface SubscriberService { /** * 增删改查 * @param user */ public void add(Subscriber user); public void delete(String userId); public void update(Subscriber user); public Subscriber get(String userId); public List<Subscriber> getAll(); public boolean checkUser(String username, String password); }
SubscriberServiceImpl.java
@Stateless public class SubscriberServiceImpl implements Serializable, SubscriberService { private static final long serialVersionUID = 1L; @EJB private SubscriberDao subscriberDao; @Override public boolean checkUser(String username, String password) { return subscriberDao.checkUser(username, password); } @Override public void add(Subscriber sysUser) { subscriberDao.save(sysUser); } @Override public void delete(String userId) { subscriberDao.delete(userId); } @Override public void update(Subscriber user) { subscriberDao.update(user); } @Override public Subscriber get(String userId) { return subscriberDao.find(userId); } @Override public List<Subscriber> getAll() { return subscriberDao.getScrollData().getResultlist(); } }
然后在action中就可以直接调用service了。。。。。。。通过@EJB标签引入SERVICE,和service引入DAO的方式是一样的。。。。
@Named("subscriber") @RequestScoped public class SubscriberAction implements Action, Serializable { private static final long serialVersionUID = 1L; private String uuid; private String userName; private String password; private Integer roleId; private String errorMessage; private Subscriber user; XXXXX其他属性 @EJB private SubscriberService subscriberService; @EJB private RoleService roleService; public SubscriberAction() { } public String get() { errorMessage = null; Subscriber user =subscriberService.get(uuid); return SUCCESS; } public String delete() { errorMessage = null; xxxxxx操作; subscriberService.delete(uuid); return SUCCESS; } public String update() { errorMessage = null; xxxxxx操作; subscriberService.update(user); return SUCCESS; } public String login() { errorMessage = null; if(!subscriberService.checkUser(userName, password)) { errorMessage = "帐号或密码有误"; return INPUT; } return SUCCESS; } 一堆getter setter。。。。。 }