——"我靠"
刚学习了springboot的数据库操作,我的脑子里就两个字——“我靠”。
这操作,相对于其他java框架来说简直是太简单了,比起jfinal数据库操作,我感觉都不差,更不要说mybatis了。
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
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
实体类:用来和数据库的表进行关联。
@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 findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
}
@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