SQL DDL to Java Entity Converter

Convert SQL DDL statements to Java entity classes with JPA, Lombok, and validation annotations support

Data Type Mapping

String Types

  • VARCHAR, CHAR, TEXT โ†’ String
  • LONGTEXT, MEDIUMTEXT โ†’ String
  • ENUM โ†’ String

Number Types

  • INT, INTEGER โ†’ Integer
  • BIGINT โ†’ Long
  • SMALLINT โ†’ Short
  • TINYINT โ†’ Byte
  • DECIMAL, NUMERIC โ†’ BigDecimal
  • FLOAT, DOUBLE โ†’ Double

Time Types

  • DATETIME, TIMESTAMP โ†’ LocalDateTime
  • DATE โ†’ LocalDate
  • TIME โ†’ LocalTime

Other Types

  • BOOLEAN, BOOL โ†’ Boolean
  • BLOB, BINARY โ†’ byte[]
  • JSON โ†’ String

Naming Convention

CamelCase:user_name โ†’ userNameaccess_date โ†’ accessDate
Underscore:user_name โ†’ user_nameaccess_date โ†’ access_date

Time Type Mapping

Time Objects Enabled:DATETIME โ†’ LocalDateTimeDATE โ†’ LocalDateTIME โ†’ LocalTime
Time Objects Disabled:DATETIME โ†’ StringDATE โ†’ StringTIME โ†’ String

Tool Overview: SQL DDL to Java Entity Converter

In Java development, especially when using Spring Boot and JPA frameworks, there's often a need to create entity classes based on database table structures. Manually writing these entity classes is not only time-consuming but also error-prone. This tool automatically converts SQL DDL statements into standard Java entity classes, greatly improving development efficiency.

What Is SQL DDL to Java Entity Converter?

SQL DDL to Java Entity Converter converts SQL DDL to Java entity and produces output ready to use.

How to Use

  1. Paste SQL DDL content or enter parameters.
  2. Choose Java entity output and set options.
  3. Review the result and copy or download.

Common Use Cases

  • SQL DDLโ†”Java entity format migration
  • Use SQL DDL data in Java entity workflows or code generation
  • Validate conversion results against specs

โ“ FAQ

Q1: Conversion failed or empty?
A: Check that the SQL DDL input is valid and complete.

Q2: Output looks different?
A: Formatting may change to match Java entity rules.

Q3: How to batch process?
A: Process in smaller chunks for stability.

โœจ Key Features

  • ๐Ÿ”„ Smart Conversion: Automatically parse CREATE TABLE statements and generate corresponding Java entity classes
  • ๐Ÿท๏ธ Multiple Annotation Support: Generate JPA, Lombok, and Bean Validation annotations
  • ๐Ÿ“Š Type Mapping: Complete mapping from SQL data types to Java types
  • โš™๏ธ Configurable Options: Customize package name, annotation generation, naming conventions, and time type mapping
  • ๐Ÿ”ง Constraint Handling: Automatically handle primary keys, foreign keys, unique constraints, default values, etc.
  • ๐Ÿ“ Code Standards: Generate code that follows Java naming conventions
  • ๐ŸŽฏ Naming Flexibility: Support both camelCase and underscore naming styles
  • โฐ Time Type Choice: Option to map time fields to time objects or strings

๐Ÿ“– Usage Examples

Basic Table Structure Conversion

Input SQL DDL:

CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL,
    age INT,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Output Java Entity:

package com.example.entity;

import java.time.LocalDateTime;
import javax.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users")
public class Users implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "username", nullable = false, unique = true)
    private String username;

    @Column(name = "email", nullable = false)
    private String email;

    @Column(name = "age")
    private Integer age;

    @Column(name = "is_active")
    private Boolean isActive;

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;
}

Complex Table Structure Conversion

Input SQL DDL:

CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    order_no VARCHAR(32) NOT NULL UNIQUE,
    user_id BIGINT NOT NULL,
    total_amount DECIMAL(10,2) NOT NULL,
    status ENUM('pending', 'paid', 'shipped', 'completed', 'cancelled') DEFAULT 'pending',
    order_data JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Output Java Entity:

package com.example.entity;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "orders")
public class Orders implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "order_no", nullable = false, unique = true)
    private String orderNo;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @Column(name = "total_amount", nullable = false)
    private BigDecimal totalAmount;

    @Column(name = "status")
    private String status;

    @Column(name = "order_data")
    private String orderData;

    @Column(name = "created_at")
    private LocalDateTime createdAt;
}

๐ŸŽฏ Application Scenarios

1. Spring Boot Project Development

// User Service Class
@Service
@Transactional
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public Users createUser(Users user) {
        // Validate username uniqueness
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new BusinessException("Username already exists");
        }
        
        // Set creation time
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setIsActive(true);
        
        return userRepository.save(user);
    }
    
    public Users updateUser(Long id, Users userUpdate) {
        Users existingUser = userRepository.findById(id)
            .orElseThrow(() -> new EntityNotFoundException("User not found"));
        
        // Update fields
        existingUser.setEmail(userUpdate.getEmail());
        existingUser.setAge(userUpdate.getAge());
        existingUser.setUpdatedAt(LocalDateTime.now());
        
        return userRepository.save(existingUser);
    }
    
    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new EntityNotFoundException("User not found");
        }
        userRepository.deleteById(id);
    }
    
    public Page<Users> findUsers(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
}

2. JPA Repository Interface

// User Data Access Layer
@Repository
public interface UserRepository extends JpaRepository<Users, Long> {
    
    // Find user by username
    Optional<Users> findByUsername(String username);
    
    // Check if username exists
    boolean existsByUsername(String username);
    
    // Find user by email
    Optional<Users> findByEmail(String email);
    
    // Find active users
    List<Users> findByIsActiveTrue();
    
    // Find users by age range
    List<Users> findByAgeBetween(Integer minAge, Integer maxAge);
    
    // Custom query: find recently registered users
    @Query("SELECT u FROM Users u WHERE u.createdAt >= :date ORDER BY u.createdAt DESC")
    List<Users> findRecentUsers(@Param("date") LocalDateTime date);
    
    // Update user status
    @Modifying
    @Query("UPDATE Users u SET u.isActive = :active WHERE u.id = :id")
    int updateUserStatus(@Param("id") Long id, @Param("active") Boolean active);
}

๐Ÿ“ Data Type Mapping Table

MySQL Type Mapping

SQL Type Java Type Description
VARCHAR, CHAR, TEXT String String types
INT, INTEGER Integer 32-bit integer
BIGINT Long 64-bit integer
SMALLINT Short 16-bit integer
TINYINT Byte 8-bit integer
DECIMAL, NUMERIC BigDecimal High-precision decimal
FLOAT Float Single-precision floating point
DOUBLE Double Double-precision floating point
BOOLEAN, BOOL Boolean Boolean value
DATETIME, TIMESTAMP LocalDateTime Date and time
DATE LocalDate Date only
TIME LocalTime Time only
JSON String JSON data
BLOB, BINARY byte[] Binary data

PostgreSQL Type Mapping

SQL Type Java Type Description
VARCHAR, TEXT String String types
INTEGER Integer 32-bit integer
BIGINT Long 64-bit integer
SMALLINT Short 16-bit integer
NUMERIC BigDecimal High-precision decimal
REAL Float Single-precision floating point
DOUBLE PRECISION Double Double-precision floating point
BOOLEAN Boolean Boolean value
TIMESTAMP LocalDateTime Timestamp
DATE LocalDate Date
TIME LocalTime Time
JSONB, JSON String JSON data
BYTEA byte[] Binary data

โš™๏ธ Configuration Options

Annotation Configuration

  • Generate JPA Annotations: Add @Entity, @Table, @Column, @Id and other JPA standard annotations
  • Generate Lombok Annotations: Add @Data, @NoArgsConstructor, @AllArgsConstructor annotations
  • Generate Validation Annotations: Add @NotNull, @Size and other Bean Validation annotations
  • Implement Serializable Interface: Make generated classes implement serialization interface

Naming Convention Configuration

  • Enable CamelCase: user_name โ†’ userName (Recommended, follows Java conventions)
  • Keep Underscore: user_name โ†’ user_name (For special requirements)

Time Type Mapping Configuration

  • Map to Time Objects: DATETIME โ†’ LocalDateTime (Recommended, type-safe)
  • Map to Strings: DATETIME โ†’ String (For compatibility considerations)

๐Ÿ”ง Usage Tips

  1. Naming Conventions: Choose camelCase or underscore naming based on project requirements
  2. Annotation Selection: You can selectively generate JPA, Lombok, and validation annotations
  3. Package Name Setting: You can customize the package name for the generated code
  4. Serialization Support: Option to implement the Serializable interface
  5. Constraint Handling: Automatically recognizes primary keys, unique constraints, default values, etc.
  6. Time Types: Choose time objects or string mapping based on business requirements

๐ŸŽ“ Learning Points

  • Understanding SQL DDL statement structure and syntax
  • Mastering Java entity class design and annotation usage
  • Learning JPA specification and Hibernate implementation
  • Understanding database design and ORM mapping best practices

This SQL DDL to Java Entity Converter is a powerful assistant for Java developers, making database entity creation simple and efficient!