如何从Java桌面应用持久化FOS_USER Bundle关联的用户数据?
Since you already have a database set up with the FOS_USER User table from your Symfony web app, here are practical, straightforward approaches to work with that data in your Java desktop application:
1. Direct JDBC Approach (Minimal Dependencies)
This is the simplest way if you want to avoid heavy frameworks. You’ll map the User table columns to a Java POJO and use raw JDBC to handle database operations.
Step 1: Create a User POJO
Match the fields to your FOS_USER table schema:
public class User { private int id; private String username; private String email; private boolean enabled; private String password; // Note: This is hashed in FOS_USER // Getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } // Add getters/setters for all other fields }
Step 2: Implement JDBC CRUD Operations
Use java.sql classes to connect and interact with your database. Example for fetching a user:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class UserDao { private static final String DB_URL = "jdbc:mysql://your-db-host:3306/your-db-name?useUnicode=true&characterEncoding=utf8"; private static final String DB_USER = "your-db-username"; private static final String DB_PASS = "your-db-password"; public User getUserByUsername(String username) { User user = null; String query = "SELECT id, username, email, enabled FROM User WHERE username = ?"; try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, username); ResultSet rs = stmt.executeQuery(); if (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setEmail(rs.getString("email")); user.setEnabled(rs.getBoolean("enabled")); } } catch (Exception e) { e.printStackTrace(); } return user; } // Add methods for create, update, delete operations following the same pattern }
2. Use Hibernate (JPA ORM)
For a more maintainable, object-oriented solution, use Hibernate to map your database table to Java objects without writing raw SQL.
Step 1: Add Dependencies (Maven Example)
Add these to your pom.xml:
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>6.4.4.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> </dependencies>
Step 2: Create a JPA Entity Class
Annotate your User class to match the FOS_USER table:
import jakarta.persistence.*; @Entity @Table(name = "User") // Quote the table name if your database treats "User" as a reserved word public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "username", length = 180, nullable = false, unique = true) private String username; @Column(name = "email", length = 180, nullable = false, unique = true) private String email; @Column(name = "enabled", nullable = false) private boolean enabled; @Column(name = "password", length = 255, nullable = false) private String password; // Getters and setters }
Step 3: Configure Hibernate
Create a hibernate.cfg.xml in your resources folder:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://your-db-host:3306/your-db-name?useUnicode=true&characterEncoding=utf8</property> <property name="hibernate.connection.username">your-db-username</property> <property name="hibernate.connection.password">your-db-password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property> <property name="hibernate.show_sql">true</property> <mapping class="com.yourpackage.User"/> </session-factory> </hibernate-configuration>
Step 4: Perform Operations with Hibernate
Example of saving a user:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class UserService { private SessionFactory sessionFactory; public UserService() { sessionFactory = new Configuration().configure().buildSessionFactory(); } public void saveUser(User user) { try (Session session = sessionFactory.openSession()) { session.beginTransaction(); session.persist(user); session.getTransaction().commit(); } } // Add methods for fetching, updating, deleting users }
3. Reuse Your Symfony Backend (REST API)
If you want to keep business logic centralized, build a REST API in Symfony to handle User operations, then call this API from your Java app using an HTTP client.
Example Java API Client
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import com.google.gson.Gson; // Use Gson/Jackson to parse JSON public class UserApiClient { private static final String API_BASE = "http://your-symfony-app-url/api/users"; private final Gson gson = new Gson(); public User getUserByUsername(String username) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(API_BASE + "?username=" + username)) .GET() .build(); try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); return gson.fromJson(response.body(), User.class); } catch (Exception e) { e.printStackTrace(); return null; } } }
Key Note on Password Handling
If you’re creating users from the Java app, remember to hash passwords using the same algorithm as FOS_USER (usually bcrypt) before storing them—never save plaintext passwords!
内容的提问来源于stack exchange,提问作者Zain Elabidine

