我正在尝试测试一小段代码,看看我是否可以使用 hibernate 连接到我的本地数据库并创建一些表并插入数据。
package service;
import model.CategoryEntry;
import model.SubCategoryEntry;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class DatabaseConnectionTest {
@Test
public void databaseConnectionIsSuccessful() {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
CategoryEntry categoryEntry = new CategoryEntry();
categoryEntry.setId(2269);
categoryEntry.setAlert(false);
categoryEntry.setLabel("Eat and Drink");
categoryEntry.setSlug("eat-drink");
List<CategoryEntry> subcategories = new ArrayList<>();
CategoryEntry subCategoryEntry1 = new CategoryEntry();
subCategoryEntry1.setId(9);
subCategoryEntry1.setAlert(false);
subCategoryEntry1.setLabel("Food");
subCategoryEntry1.setSlug("food");
subCategoryEntry1.setParent(categoryEntry);
subcategories.add(subCategoryEntry1);
categoryEntry.setSubcategories(subcategories);
try {
session.beginTransaction();
session.persist(categoryEntry);
session.getTransaction().commit();
session.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
}
}
和实体类:
package model;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class CategoryEntry {
@Id
private int id;
private boolean alert = false;
private String label;
private String slug;
}
相关分类