springboot之數據庫操作1——(spring data jpa)
——"我靠"
剛學習了springboot的數據庫操作,我的腦子裏就兩個字——“我靠”。
這操作,相對於其他java框架來說簡直是太簡單了,比起jfinal數據庫操作,我感覺都不差,更不要說mybatis了。
jpa是什麼?
步驟
1.添加相關jar包/依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.添加配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
3.添加實體類和Dao
實體類:用來和數據庫的表進行關聯。
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
//省略getter settet方法、構造方法
}
Dao:一個面向對象的數據庫接口,用來調用操作數據庫的方法的。
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
}
4.測試
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
String formattedDate = dateFormat.format(date);
userRepository.save(new User("aa1", "[email protected]", "aa", "aa123456",formattedDate));
userRepository.save(new User("bb2", "[email protected]", "bb", "bb123456",formattedDate));
userRepository.save(new User("cc3", "[email protected]", "cc", "cc123456",formattedDate));
Assert.assertEquals(9, userRepository.findAll().size());
Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "[email protected]").getNickName());
userRepository.delete(userRepository.findByUserName("aa1"));
}
}
具體:http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html