@Table(name="user")
@Entity
public class User {
@GeneratedValue
@Id
private Integer id;
private String username;
private String password;
//省略getter setter
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}
}
UserRepository接口
public interface UserRepository extends Repository<User, Integer>{
public User getByUsername(String username);
public User getById(Integer id);
}
测试类
public class Test {
private ApplicationContext applicationContext = null;
{
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@org.junit.Test
public void testDataSource() {
DataSource dataSource = applicationContext.getBean(DataSource.class);
System.out.println(dataSource);
}
@org.junit.Test
public void testJPA() {
//测试自动生产数据库表
}
@org.junit.Test
public void testHelloWorld() {
UserRepository userRepository = applicationContext.getBean(UserRepository.class);
User user = null;
// user = userRepository.getByUsername("admin");
user = userRepository.getById(1);
System.out.println(user);
}
}
你没看错,就这么点代码。数据库中的表是根据实体类自动生成的,测试类中的testHelloWorld方法可以从数据库中取出user对象。
本文源码下载:
------------------------------------------分割线------------------------------------------
具体下载目录在 /2015年资料/10月/25日/Spring Data学习笔记-Hello World/
------------------------------------------分割线------------------------------------------