Hibernate проблема с SessionFactory

303
03 ноября 2017, 08:42

При conection в базу, ошибка NoSuchMethodError: org.hibernate.cfg.annotations.reflection.JPAMetadataProvider‌​.<init>(Lorg/hiberna‌​te/boot/spi/Metadata‌​BuildingOptions;)

hibernateUtil :

public class HiberhateUtil {

private static SessionFactory sessionFactory = null;
   public static SessionFactory getSesssionFactory() {
try{
    // A SessionFactory is set up once for an application
     sessionFactory = new MetadataSources(new StandardServiceRegistryBuilder().
                configure("hibenate.cfg.xml").build()).
                getMetadataBuilder().build().
                getSessionFactoryBuilder().build();
        return sessionFactory;
}
catch(Throwable ex){
    System.err.println("Session Factory creation failed: " + ex);
    throw new ExceptionInInitializerError(ex);
}

} }

User :

@Entity
@Table(name = "users")
public class User {
    public static final String SELECT_USER_COUNT_BY_LOGIN = "select_user_count_by_login";
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "date", columnDefinition = "Integer", nullable = false)
    private int date;
    @Column(name = "name", columnDefinition = "varchar(255)", nullable = false)
    private String name;
    @Column(name = "userName", columnDefinition = "varchar(256)", nullable = false)
    private String userName;
    @Column(name = "password", columnDefinition = "varchar(256)", nullable = false)
    private String password;
    @Column(name = "country", columnDefinition = "varchar(256)", nullable = false)
    private String country;
    @Column(name = "phone", columnDefinition = "varchar(256)", nullable = false)
    private String phone;
    @Column(name = "email", columnDefinition = "varchar(256)", nullable = false, unique = true)
    private String email;

xml :

 <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:5432/personal?useSSL=false</property>
            <property name="hibernate.connection.username">postgres</property>
            <property name="hibernate.connection.password">root</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <mapping class="users.User"></mapping>
            </session-factory>
    </hibernate-configuration>
Answer 1
    ну, во-первых, я не понял юмора с Вашей конфигурацией
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.password">root</property>
            <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/personal</property>
            <property name="hibernate.connection.username">postgres</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    Вы что используете: постгрии или мускул? 
    Я так понимаю, что второй вариант. Меняйте настройки и обратите внмание на диалект. А потом напишите, каков результат выполнения...
        <property name="hibernate.connection.url">jdbc:mysql://...?useSSL=false</property>
        <property name="hibernate.connection.username"></property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
А фабрику у хибернейта получают так:
SessionFactory sessionFactory = 
            new MetadataSources(new StandardServiceRegistryBuilder().
                    configure("hibernate.cfg.xml").build()).
                    getMetadataBuilder().build().
                    getSessionFactoryBuilder().build();
Answer 2
private static SessionFactory buildSessionAnnotationFactory() {
    try {
        Configuration configuration = new Configuration();
        configuration.configure("/hibenate.cfg.xml");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
Answer 3
package users;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Main {
    public static void main(String[] args) {
        User user = new User
        (111, "TestName", "TestUserName", "TestPassword", "TestCountry", "TestPhone", "TestEmail");
        SessionFactory sesssionFactory = getSesssionFactory();
        Session session = sesssionFactory.openSession();
        session.beginTransaction();
        session.saveOrUpdate("User", user);
        session.getTransaction().commit();
        session.close();
        sesssionFactory.close();
    }
    public static SessionFactory getSesssionFactory() {
        try {
            SessionFactory sessionFactory
                    = new MetadataSources(new StandardServiceRegistryBuilder().
                            configure("hibernate.cfg.xml").build()).
                            getMetadataBuilder().build().
                            getSessionFactoryBuilder().build();
            return sessionFactory;
        } catch (HibernateException ex) {
            System.err.println("Session Factory creation failed: " + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
}

package users;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
    public static final String SELECT_USER_COUNT_BY_LOGIN = "select_user_count_by_login";
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "date", columnDefinition = "Integer", nullable = false)
    private int date;
    @Column(name = "name", columnDefinition = "varchar(255)", nullable = false)
    private String name;
    @Column(name = "userName", columnDefinition = "varchar(256)", nullable = false)
    private String userName;
    @Column(name = "password", columnDefinition = "varchar(256)", nullable = false)
    private String password;
    @Column(name = "country", columnDefinition = "varchar(256)", nullable = false)
    private String country;
    @Column(name = "phone", columnDefinition = "varchar(256)", nullable = false)
    private String phone;
    @Column(name = "email", columnDefinition = "varchar(256)", nullable = false, unique = true)
    private String email;
    public User() {}
    public User(int date, String name, String userName, String password, String country, String phone, String email) {
        this.date = date;
        this.name = name;
        this.userName = userName;
        this.password = password;
        this.country = country;
        this.phone = phone;
        this.email = email;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getDate() {
        return date;
    }
    public void setDate(int date) {
        this.date = date;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
<hibernate-configuration>
  <session-factory>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:5432/personal?useSSL=false</property>
      <property name="hibernate.connection.username">postgres</property>
      <property name="hibernate.connection.password">root</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.useUnicode">false</property>
      <property name="hibernate.connection.characterEncoding">UTF-8</property>
      <property name="hibernate.hbm2ddl.auto">create</property>
      <property name="hibernate.show_sql">false</property>
      <property name="connection.pool_size">10</property>
      <mapping class="users.User"></mapping>
  </session-factory>
</hibernate-configuration>
и зависимости градла
dependencies {
    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'
    compile group: 'org.hibernate', name: 'hibernate-validator', version: '6.0.2.Final'
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.43'
}
так все будет работать
READ ALSO
Отправка запроса через Postman с использованием ЭЦП

Отправка запроса через Postman с использованием ЭЦП

Приветствую! Есть url, на который необходимо послать запрос с использованием ЭЦП(электронная цифровая подпись), у меня есть private и public ключи,...

332
Protected методы в интерфейсах Java 9

Protected методы в интерфейсах Java 9

Появятся ли protected/package-private методы в интерфейсах Java 9 или добавят только private?

229
Как работать со сканером в java? [требует правки]

Как работать со сканером в java? [требует правки]

Вот допустим я создал сканер чтобы счесть вводимые данныеКак мне их использовать в конструкция if, switch, for и т

196