日期:2014-05-18 浏览次数:20665 次
package info.bishe.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
private int id;
private String username;
private String password;
@Id
@GeneratedValue //无法生成自动增长的主键
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
package info.bishe.dao;
import info.bishe.model.User;
public interface UserDAO {
public void save(User u);
}
package info.bishe.dao.imp;
import info.bishe.dao.UserDAO;
import info.bishe.model.User;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Component;
@Component("userDAO")//可以指定名称
public class UserDAOimp implements UserDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void save(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
package info.bishe.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.sun.xml.internal.ws.api.PropertySet.Property;
import info.bishe.dao.UserDAO;
import info.bishe.dao.imp.UserDAOimp;
import info.bishe.model.User;
@Component("userService")
public class UserService {
private UserDAO userDAO;
@PostConstruct
public void init(){
System.out.println("init");
}
public UserDAO getUserDAO() {
return userDAO;
}
//@Autowired
@Resource(name="userDAO")
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public void add(User user){
this.userDAO.save(user);
}
@PreDestroy
public void destroy(){
System.out.println("destroy");
}
}