org.springframework.boot spring-boot-starter-data-jpa
此处是扩展部分(扩展部分纯属扯淡可以不看) Spring Data JPA 官方地址;(https://spring.io/projects/spring-data-jpa) 里面有很详细的资料,可惜是英文的。
第二步:添加数据库驱动依赖
mysql mysql-connector-java
第三步:在application.properties(或者application.yum)中配置数据库和jpa的相关属性
#DB Configuration: spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ceshi?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root #JPA Configuration: spring.jpa.database=MySQL spring.jpa.show-sql=true spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
第四部:创建实体
@Entity public class User{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String name; public Long getId() { return id; } public void setId(Long 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; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + ''' + ", password='" + password + ''' + ", name='" + name + ''' + '}'; } }
第五步:编写UserRepository
public interface UserRepository extends JpaRepository{ public List findAll(); }
第六步:编写测试类
@RunWith(SpringRunner.class) @SpringBootTest(classes=MySpringBootApplication.class) public class JpaTest { @Autowired private UserRepository userRepository; @Test public void test(){ Listusers = userRepository.findAll(); System.out.println(users); } }
第七部:打印测试一下
忘记写数据库的事情了粘贴一些
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户编号', `name` varchar(20) DEFAULT NULL COMMENT '用户名拼音', `password` char(32) DEFAULT NULL COMMENT '密码', `username` varchar(20) DEFAULT NULL COMMENT '用户名', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)