日期:2014-05-20 浏览次数:21151 次
package com.ssh.service.impl; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ssh.bean.User; import com.ssh.service.UserService; public class UserServiceImplTest { public static UserService service; @BeforeClass public void setUpBeforeClass(){ ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); service = (UserServiceImpl)context.getBean("userServiceImpl"); } @Test public void testSave(){ User u = new User(); u.setName("zhangsan"); u.setPassword("123"); service.addUser(u); } }
package com.ssh.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ssh.bean.User;
import com.ssh.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService {
    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    @Transactional(propagation=Propagation.SUPPORTS)
    public void addUser(User user) {
        getSessionFactory().getCurrentSession().persist(user);
    }
    public void delete(String name) {
        getSessionFactory().getCurrentSession()
                           .createQuery("delete User u where u.name=:name")
                           .setString("name", name)
                           .executeUpdate();
    }
    public User find(String name) {
        User user =(User)getSessionFactory().getCurrentSession().load(User.class,name);
        return user;
    }
    public List<User> list() {
        return getSessionFactory().getCurrentSession().createQuery("from User").list();
         
    }
    public void update(User user) {
        getSessionFactory().getCurrentSession()
                           .createQuery("update User u set u.name=:newName,u.password=:newPassword")
                           .setString("newName", user.getName())
                           .setString("newPassword", user.getPassword())
                           .executeUpdate();
    }
}