1. 自定义配置
1.1 application.properties
com.test.title=测试标题
com.test.description=测试内容
1.2 自定义配置类
@Component public class TestProperties { @Value("${com.boot.title}") private String title; @Value("${com.boot.description}") private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
2. 配置日志输出地址和输出级别
# 配置log输出地址和输出级别,path为本机的log地址,logging.level 后面可以根据包路径配置不同资源的log级别 logging.path=/user/local/log logging.level.com.boot.springboot=DEBUG logging.level.org.springframework.web=INFO logging.level.org.hibernate=ERROR
3. 数据库操作
spring data jpa使用
3.1 添加数据库操作相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
3.2 添加配置文件
# mysql数据库操作相关配置 spring.datasource.url=jdbc:mysql://localhost:3306/hzf?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
注意:上面如果不加serverTimezone=GMT%2B8会报错,说明设置时区有问题,GMT%2B8代表是东八区
3.3 添加实体类
@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;
3.4 构建dao
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
}
4. 调用测试
5. 上面涉及到的注解:
serialVersionUID作用:Java的序列化机制是通过判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常,即是InvalidCastException。
nullable=false:字段保存时必须有值,传Null去save会报错,