<!--增加数据源-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
–配置数据源application.properties
##配置数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/sms?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
–配置dbcp2连接池application.properties
##配置dbcp2连接池
#初始大小
spring.datasource.dbcp2.initial-size=10
#最大
spring.datasource.dbcp2.max-total=15
#最大等待时间,单位为秒
spring.datasource.dbcp2.max-wait-millis=30000
–配置jpa。application.properties
##配置jpa
#显示SQL
spring.jpa.show-sql=true
#将实体管理对象(操作对象)与页面视图绑定起来,只有视图关闭了才释放
spring.jpa.open-in-view=true
#支持自动转变驼峰命名法
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
@Entity
@Table(name = "tb_student")
@Data
public class Student implements Serializable {
private static final long serialVersionUID = 456910787545073395L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "student_id")
private Integer studentId;//INT(11) '学生编号',
@Column(name = "student_name")
private String studentName;//VARCHAR(50) '学生名' COLLATE ,
@Column(name = "student_pwd")
private String studentPwd;//VARCHAR(50) '密码' COLLATE ,
}
public interface StudentRepository extends Repository<Student,Integer> {
List<Student> findAll();
}
public class ApplicationTests {
@Autowired
private StudentRepository studentRepository;
@Test
public void findAll() {
List<Student> students = studentRepository.findAll();
for (Student student : students) {
System.out.println("学生名:"+student.getStudentName());
}
}
}
答:SpringDataJPA支持接口规则查询。通过设置方法的规则,来决定查询的行为。
规则如下:
内置的查询方法find、read、get开头。
内置的统计查询方法使用count开头
内置的删除方法使用delete开头
–示例代码
/**
* 泛型参数1,表示操作的实体类类型
* 参数2:Id字段的类型
*/
public interface StudentRepository extends Repository<Student,Integer> {
//查询所有数据
List<Student> findAll();
//通过条件查询
List<Student> findByStudentNameLike(String studentName);
//统计表的所有记录
long countAll();
}
当使用delete规则删除时,需要添加 @Transactional注解,否则会报错。
当使用@Query自定义语句时,需要添加@Modifying 和@Transactional,否则会报错
–Repository代码
/**
* 泛型参数1,表示操作的实体类类型
* 参数2:Id字段的类型
*/
public interface StudentRepository extends JpaRepository<Student,Integer> {
List<Student> findByStudentNameLike(String studentName);
//删除,修改的操作需要加上事务
@Transactional
void deleteStudentByStudentName(String studentName);
@Transactional
//@Query(value表示jpql或者sql语句,nativeQuery = true表示即可以使用原生SQL进行查询)
@Query("delete from Student s where s.studentName = :name")
@Modifying //DML操作
void deleteByName(String name);
@Query(value = "select * from tb_student",nativeQuery = true)
List<Student> sqlQuery();
}
可以参考:https://www.cnblogs.com/zhaobingqing/p/6864223.html