我的JPA实体类中有这样声明的字符串数组
private String[] suggestion = new String[3];
我通过在'resource'文件夹中创建sql文件来插入数据。如何使用INSERT INTO .. VALUES (..) ???
答案 0 :(得分:1)
您可以使用H2来检查此工作示例,因为我已经对其进行了测试。
首先将以下属性添加到application.properties文件中:
# To See H2 Console in Browser:
# http://localhost:8080/h2-console
# Enabling H2 Console
spring.h2.console.enabled=true
# ===============================
# DB
# ===============================
spring.datasource.url=jdbc:h2:~/test
#jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
# ===============================
# JPA / HIBERNATE
# ===============================
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
控制器代码:
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@PostMapping(value = "/test")
public Person checkTest() {
System.out.println("PWan");
return personService.savePerson();
}
}
服务代码:
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public Person savePerson() {
Person p = new Person();
p.setFullname("Pawan");
personRepository.save(p);
return p;
}
}
存储库代码:
public interface PersonRepository extends JpaRepository<Person, Long>{
public Person findByfullname(String name);
public Optional<Person> findById(Long id);
}
请找到以下链接以供参考:
如果有任何问题,请通知我。
答案 1 :(得分:0)
您可以实现Application Listener来侦听spring的Context Refreshed Event,并重写onApplicationEvent()方法以将数据插入数据库。
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class Bootstrap implements ApplicationListener<ContextRefreshedEvent> {
// Array Initialization
private String[] suggestion = new String[3];
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
initData();
}
private void initData(){
// Loop through array
for (String item : suggestion){
// Insert data using a repository
}
}
}
初始化或刷新ApplicationContext时引发此事件。 Link转换为Java文档。