MyEclipse hibernate3.2注解使用

在MyEclipse加入hibernate方法非常简单,右击工程,选择MyEclipse,再选择hibernate capability
MyEclipse也提交了非常好的可视工具,使领域对象和数据库表关联起来,使的使用他们非常简单。选择Myeclipse Hibernate视图。然后新建连接。通常要选择dirver name,url,username,password。
选择某一数据库,然后打开连接,在指定的表上右击Hibernate Reverse Engineer。最主要的就是主键的生成方式,一般都选择native.
请看下面的一个例子
使用的是MySQL数据库及对应的驱动
create table user (
id int unsigned not null auto_increment,
username varchar(50),
password varchar(50),
primary key(id)                                
) ;
insert into user (username, password) values ('dog','dog');
insert into user (username, password) values ('cat','cat');
insert into user (username, password) values ('tiger','tiger');
insert into user (username, password) values ('pig','pig');

建立工程,加入hibernate capability,建立hibernate连接,逆向工程一个表。
AbstractUser.java
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class AbstractUser implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
// Constructors
/** default constructor */
public AbstractUser() {
}
/** full constructor */
public AbstractUser(String username, String password) {
this.username = username;
this.password = password;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "username", length = 50)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password", length = 50)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}

User.java
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "user", catalog = "example")
public class User extends AbstractUser implements java.io.Serializable {
// Constructors
/** default constructor */
public User() {
}
/** full constructor */
public User(String username, String password) {
super(username, password);
}
}

UserService.java
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class UserService {
public static void main(String[] args) {
// TODO Auto-generated method stub
       SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
       Session session = sessionFactory.openSession();
       Query query = session.createQuery("from User");
       Iterator ite = query.iterate();
       while(ite.hasNext()){
       User user = (User)ite.next();
       System.out.println(user.getUsername());
       }    
}
}

输出结果
dog
cat
tiger
pig

你可能感兴趣的:(java,Hibernate,mysql,MyEclipse)