我是 Spring Boot 新手,我面临着无法自行使用互联网解决的问题。我正在尝试将应用程序连接到 xampp localhost 数据库,但遇到了这个问题,我添加了所有必要的依赖项,这是我的简单代码:
主课
package com.example.kilohokla;
@SpringBootApplication
@EnableJpaRepositories("com.example.kilohokla")
@ComponentScan(basePackages = {"com.example.kilohokla"})
public class HelloApplication extends Application {
private ConfigurableApplicationContext applicationContext;
@Override
public void init() throws Exception {
applicationContext = SpringApplication.run(HelloApplication.class);
}
@Override
public void start(Stage stage) throws IOException {
// AccountsRepository accountsRepository = applicationContext.getBean(AccountsRepository.class);
Logger logger = LogManager.getLogger(HelloApplication.class);
//
// Accounts sampleUser = new Accounts();
// sampleUser.setName("Sample");
// sampleUser.setSurname("User");
// sampleUser.setEmail("[email protected]");
// sampleUser.setPhoneNumber("123456789");
// sampleUser.setPassword("password");
// sampleUser.setLogin("sample");
// Save the sample user to the database
// accountsRepository.save(sampleUser);
logger.info("Applicaton has launched succesfully");
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("login-view.fxml"));
Font.loadFont(getClass().getResourceAsStream("/com/example/kilohokla/fonts/Inter/Inter.ttf"), 32);
Scene scene = new Scene(fxmlLoader.load());
stage.setTitle("Kilohokla");
stage.setScene(scene);
stage.show();
}
@Override
public void stop() throws Exception {
applicationContext.stop();
}
public static void main(String[] args) {
launch(HelloApplication.class, args);
}
}
回购:
@Repository
public interface AccountsRepository extends JpaRepository<Accounts, Long> {
void save(Accounts account);
}
实体:
@Entity
@Table(name = "accounts")
public class Accounts {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long accountID;
@ManyToOne
@JoinColumn(name = "permissionID")
private Permissions permission;
private String name;
private String surname;
private String email;
private String phoneNumber;
private String password;
private String login;
@ManyToOne
@JoinColumn(name = "teamID")
private Teams team;
控制器
@Controller
public class AccountsController {
@Autowired
private AccountService accountService;
public AccountsController() {
}
@PostMapping("/addAccount")
public String addAccount(Accounts account) {
accountService.addAccount(account);
return "redirect:/";
}
}
服务:
@Service
public class AccountService {
@Autowired
private AccountsRepository accountsRepository;
@Transactional
public void addAccount(Accounts account) {
accountsRepository.saveAndFlush(account);
}
}
pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>17</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
我尝试了 spingBoot 文档、堆栈帖子和 yt 视频建议的所有解决方案,我只想启动应用程序;(
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>21.0.3</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>21.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
xampp 数据库是 MariaDB 而不是 MySQL。
module com.example.demo {
requires spring.boot;
requires spring.boot.autoconfigure;
requires spring.context;
requires spring.web;
requires javafx.controls;
requires javafx.fxml;
requires jakarta.persistence;
requires spring.beans;
requires spring.data.jpa;
opens com.example.demo to spring.core, spring.beans, spring.context, spring.boot, spring.boot.autoconfigure, javafx.fxml;
//opens com.example.demo to javafx.fxml;
exports com.example.demo;
}
将 com.example.demo 更改为您的包名称。
spring.application.name=demo
spring.datasource.url=jdbc:mariadb://localhost:3306/exampledb
spring.datasource.username=example-user
spring.datasource.password=my_Passw0rd!
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
mvn clean package
创建数据库
CREATE DATABASE exampledb;
授予您的数据库用户xxx(如
example-user
)拥有特权
SQL命令:
CREATE USER 'example-user'@'localhost' IDENTIFIED BY 'my_Passw0rd!';
CREATE USER 'example-user'@'%' IDENTIFIED BY 'my_Passw0rd!';
GRANT ALL PRIVILEGES ON exampledb.* TO 'example-user'@'localhost';
GRANT ALL PRIVILEGES ON exampledb.* TO 'example-user'@'%';
FLUSH PRIVILEGES;
java --module-path /home/demo/javafx-sdk-21.0.3/lib --add-modules javafx.controls,javafx.fxml -jar target/demo-0.0.1-SNAPSHOT.jar
--module-path /home/demo/javafx-sdk-21.0.3/lib 指向您的javafx SDK lib(下载javafx sdk并解压到某个目录) --添加模块 javafx.controls,javafx.fxml
package com.example.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Person {
public Person() {
super();
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person, Long> {
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List<Person> getAllPersons() {
return personRepository.findAll();
}
public Optional<Person> getPersonById(Long id) {
return personRepository.findById(id);
}
public Person createOrUpdatePerson(Person person) {
return personRepository.save(person);
}
public void deletePerson(Long id) {
personRepository.deleteById(id);
}
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/persons")
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping
public List<Person> getAllPersons() {
return personService.getAllPersons();
}
@GetMapping("/{id}")
public ResponseEntity<Person> getPersonById(@PathVariable("id") Long id) {
return personService.getPersonById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Person> createPerson(@RequestBody Person person) {
return new ResponseEntity<>(personService.createOrUpdatePerson(person), HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Person> updatePerson(@PathVariable("id") Long id, @RequestBody Person person) {
if (!personService.getPersonById(id).isPresent()) {
return ResponseEntity.notFound().build();
}
person.setId(id);
return new ResponseEntity<>(personService.createOrUpdatePerson(person), HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deletePerson(@PathVariable("id") Long id) {
if (!personService.getPersonById(id).isPresent()) {
return ResponseEntity.notFound().build();
}
personService.deletePerson(id);
return ResponseEntity.noContent().build();
}
}
运行此应用程序来测试您的 JavaFX + Spring Boot 应用程序。
在 JavaFX + Spring Boot 应用程序启动后运行此应用程序。
我没有把它放在JavaFX + Spring Boot应用程序中,但你可以稍后自己做。
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/api/persons");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String jsonInputString = "{\"firstName\": \"Jane\", \"lastName\": \"Doe\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
connection.disconnect();
}
}
检查您的数据库内容 - 查找新记录
或者您可以找到 javafx + spring boot 应用程序控制台输出:
Hibernate: insert into person (first_name,last_name) values (?,?)