彩虹制造者
发布于

休眠中的连接问题

我需要使用 hibernate 将我的 song 类与数据库连接起来。但是,hibernate 并没有连接和执行查询。我使用了几种方法和 hibernate 的几个依赖项,但它仍然没有执行。

Song.java

  package com.projects.demohibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name="Song")
public class Song {

    @Id
    @Column(name = "id")
    private int id;
    @Column(name = "Songname")
    private String Songname;

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

    public Song(int id, String songname, String artist) {
        this.id = id;
        Songname = songname;
        Artist = artist;
    }

    public void setId(int id) {
        this.id = id;
    }
    public void setSongname(String songname) {
        Songname = songname;
    }
    public void setArtist(String artist) {
        Artist = artist;
    }
}

我的主文件 Source.java

  package com.projects.demohibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Source {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();

        configuration.configure("hibernate.cfg.xml");

        configuration.addAnnotatedClass(Song.class);
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        try (Session session = sessionFactory.openSession()) {
            Song song1 = new Song();
            song1.setId(1);
            song1.setSongname("Cameo");
            song1.setArtist("James Cameo");
            System.out.println("Song saved");
            session.beginTransaction();
            session.save(song1);
            session.getTransaction().commit();
            sessionFactory.close();

        }
    }
}

我的配置文件

  <?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="hibernate.connection.url">jdbc:mysql://localhost:3306/Song</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <!-- DB schema will be updated if needed -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.show_sql">true</property>
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>


  </session-factory>
</hibernate-configuration>

我需要在 Hibernate 的帮助下将我的 Song 类与我的 MySql 数据库连接起来。

浏览 (20)
点赞
收藏
1条评论
Klustron小助手
尝试将 Song 文件中的 javax 包切换到 jakarta 包 在 pom.xml 文件中添加依赖项 &lt;dependency&gt; &lt;groupId&gt;jakarta.servlet&lt;/groupId&gt; &lt;artifactId&gt;jakarta.servlet-api&lt;/artifactId&gt; &lt;version&gt;5.0.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt;
点赞
评论