Home > Software engineering >  Hibernate doesn't creating table based on entity
Hibernate doesn't creating table based on entity

Time:11-29

After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.

I checked hibernate config, but can't find where is the problem. I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.

If there are any ideas, please let me know. Thanks.

Entity class:

package com.game.entity;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(schema = "rpg", name = "player")
public class Player {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "name", length = 12, nullable = false)
    private String name;
    @Column(name = "title", length = 30, nullable = false)
    private String title;
    @Column(name = "race", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private Race race;
    @Column(name = "profession", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private Profession profession;
    @Column(name = "birthday", nullable = false)
    private Date birthday;
    @Column(name = "banned", nullable = false)
    private Boolean banned;
    @Column(name = "level", nullable = false)
    private Integer level;

    public Player() {
    }

    public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
        this.id = id;
        this.name = name;
        this.title = title;
        this.race = race;
        this.profession = profession;
        this.birthday = birthday;
        this.banned = banned;
        this.level = level;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Race getRace() {
        return race;
    }

    public void setRace(Race race) {
        this.race = race;
    }

    public Profession getProfession() {
        return profession;
    }

    public void setProfession(Profession profession) {
        this.profession = profession;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Boolean getBanned() {
        return banned;
    }

    public void setBanned(Boolean banned) {
        this.banned = banned;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }
}

Repository class:

package com.game.repository;

import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;

@Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {

    private final SessionFactory sessionFactory;

    public PlayerRepositoryDB() {
        Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    @Override
    public List<Player> getAll(int pageNumber, int pageSize) {
        try(Session session = sessionFactory.openSession()){
            NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
            nativeQuery.setFirstResult(pageNumber * pageSize);
            nativeQuery.setMaxResults(pageSize);
            return nativeQuery.list();
        }
    }

Hibernate configuration:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
    <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="connection.username">root</property>
    <property name="connection.password">1234</property>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
    <property name="show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
  </session-factory>

</hibernate-configuration>

Full project code with pom.xml is available by link: https://github.com/gamlethot/project-hibernate-1

CodePudding user response:

1-Hibernate does not recognize your repository. You should not mark repo classes as @Repository because they are not interfaces and in your example they are working like a service. So they can be @Service.

2-Do not implement IPlayerRepository. Mark it as @Repository and just autowire it to your service classes (or use constructor injection and just use like a variable) Like:

@Service
public class PlayerRepositoryDB {

private IPlayerRepository playerRepository;

public PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR
this.playerRepository = playerRepository;...

3- DB repository classes are implementing IPlayerRepository but it must be marked as @Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).

Like:

    @Repository
    public interface IPlayerRepository extends JpaRepository<Player, Long> {
//Here are the methods;
}

Here, the Long is the type of primary key of Player class.

CodePudding user response:

Hibernate XML:

   <property name="hibernate.connection.CharSet">utf8mb4</property>
   <property name="hibernate.connection.characterEncoding">UTF-8</property>
   <property name="hibernate.connection.useUnicode">true</property>

Connection url:

db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4

As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.

Spring/Hibernate filter:

<form accept-charset="UTF-8">
  • Related