小编Dat*_*eus的帖子

JPA(Hibernate) - 会话/事务和延迟加载

我有一个Java EE项目,MySQL数据库是用ORM管理的.我在Hibernate上做了很多工作来了解我做错了什么,我认为我理解会话/事务,但我不知道如何在我的案例/架构中解决这个问题.

我有一个项目和一个人与一个连接表的双向n:m关系.该项目是地图所有者.现在我想删除一个连接到Project的Person.

所以我想,我可以这样做:

Person person = findPersonById(personId);
Set<Project> projects = person.getProjects();
Iterator<Project> iterator = projects.iterator();
while (iterator.hasNext()) {
    Project project = iterator.next();
    if (project.getPersons().contains(person)) {
        project.getPersons().remove(person);
        projectDao.updateProject(project);
    }
}
personDao.removePerson(personId);
Run Code Online (Sandbox Code Playgroud)

但是我在这一行中收到错误:

Iterator<Project> iterator = projects.iterator();
Run Code Online (Sandbox Code Playgroud)

但它似乎与以下有关:

Person person = findPersonById(personId);
Run Code Online (Sandbox Code Playgroud)

和:

public Person findPersonById(int personId) {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session sess = sessionFactory.getCurrentSession();

    Transaction tx = sess.beginTransaction();
    try {
        Person person = (Person)sess.createQuery("from Person where id = "+personId).list().get(0);
        tx.commit();
        return person;
    }
    catch (IndexOutOfBoundsException ex) {
        return null; …
Run Code Online (Sandbox Code Playgroud)

java hibernate lazy-loading

2
推荐指数
1
解决办法
5613
查看次数

java.lang.IncompatibleClassChangeError

我正在尝试一对一的JPA注释.但得到以下错误

Exception in thread "main" java.lang.IncompatibleClassChangeError: class org.hibernate.cfg.ExtendedMappings has interface org.hibernate.cfg.Mappings as super class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.hibernate.cfg.AnnotationConfiguration.createExtendedMappings(AnnotationConfiguration.java:182)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:272)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1377)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at com.HiberAnnJS.main(HiberAnnJS.java:21)
Run Code Online (Sandbox Code Playgroud)

我不知道自己要做什么.

hibernate

2
推荐指数
1
解决办法
2万
查看次数

使用SUM和COUNT的JPQL本机查询

我试图运行以下代码:

public BigDecimal valuate(String searchTerms, String categoryPath) {
    Query query = em.createNativeQuery("SELECT SUM(maxBidAmount) / COUNT(maxBidAmount) FROM Item WHERE MATCH(title) AGAINST(':searchTerms') AND categoryPath=':categoryPath'", Double.class);
    query.setParameter("searchTerms", searchTerms);
    query.setParameter("categoryPath", categoryPath);
    double value = (double) query.getSingleResult();
    return new BigDecimal(value);
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到以下异常:

Exception Description: Missing descriptor for [class java.lang.Double].
Run Code Online (Sandbox Code Playgroud)

当我删除时Double.class,我得到一个不同的例外.

所以,我只是想知道在JPQL中使用COUNT和SUM的正确方法.

java sql jpa eclipselink jpql

2
推荐指数
1
解决办法
1万
查看次数

接口的泛型、通配符和超级/扩展

我有以下 jpa 实体继承层次结构:

  • 抽象帐户
  • ChildminderAccount 扩展帐户
  • ParentAccount 扩展帐户

我希望与我的 DAO 接口具有相同类型的继承层次结构,即三个接口:

  • 账户DAO
  • ChilminderAccountDAO
  • 父账户DAO

例如,这是我的基本 DAO 接口,它将包含 ChilminderAccountDAO 和 ParentAccountDAO 接口的通用方法:

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.bignibou.domain.Account;

public interface AccountDAO extends CrudRepository<Account, Integer> {

    @Modifying
    @Transactional
    @Query("UPDATE Account a SET a.accountValidated = false WHERE a.accountToken = ?1")
    int deactivateAccountFromToken(String accountToken);

    @Modifying
    @Transactional
    @Query("UPDATE Account a SET a.accountValidated = true WHERE a.accountToken = ?1")
    int reactivateAccountFromToken(String accountToken);

    @Query("SELECT COUNT(a) FROM Account a WHERE a.accountEmailAddress = …
Run Code Online (Sandbox Code Playgroud)

generics entity interface wildcard

2
推荐指数
1
解决办法
1954
查看次数

是否可以在 sqlite 中使用“索引”作为列名?

是否可以index在sqlite中用作列名?

当我尝试执行此查询时,它是使用 hibernate/jpa 生成的:

select
    metadatait0_.id as id25_,
    metadatait0_.guid as guid25_,
    metadatait0_.index as index25_,
    metadatait0_.library_section_id as library7_25_,
    metadatait0_.metadata_type as metadata4_25_,
    metadatait0_.parent_id as parent5_25_,
    metadatait0_.title as title25_ 
from
    metadata_items metadatait0_
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
...
Caused by: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "index": syntax error)
Run Code Online (Sandbox Code Playgroud)

sqlite hibernate

2
推荐指数
1
解决办法
1682
查看次数

如何处理Bean验证异常

我按照以下课程:

@Entity
public class Car {


    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "OWNER_ID")       
    private Owner owner;

    @NotNull()
    @Column(nullable = false)
    private String make;

    @NotNull() 
    @Column(nullable = true)
    private String model;


    @Column(nullable = false)
    private String gears;

    // More fields
Run Code Online (Sandbox Code Playgroud)

假设我正在尝试对象和一个字段,例如make字段,该字段为null,这是不应该的.抛出以下异常:

WARNING: EJB5184:A system exception occurred during an invocation on EJB CarEJB, method: public se.while_se.domain.Car se.while_se.business.CarEJB.createCar(se.while_se.domain.Car)
Sep 09, 2012 12:37:37 PM com.sun.ejb.containers.BaseContainer postInvoke
WARNING: 
javax.ejb.EJBException
        at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
        at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
        at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
        at …
Run Code Online (Sandbox Code Playgroud)

java bean-validation

1
推荐指数
1
解决办法
6995
查看次数

获取错误:架构不能包含两个具有相同名称的全局组件

配置Hibernate时,我的配置文件中出现以下错误.

Referenced file contains errors (http://www.springframework.org/schema/beans/spring-beans-3.1.xsd)
Run Code Online (Sandbox Code Playgroud)

当我查看"更多详情"时,它给了我以下内容:

sch-props-correct.2: A schema cannot contain two global components with the same name; this schema contains two occurrences of 'http://www.springframework.org/schema/beans,identifiedType'.
Run Code Online (Sandbox Code Playgroud)

我有一个applicationContext.xml文件,其架构定义(我导入我的hibernate-context.xml文件)如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

..
..
<!-- Imports datasource configuration -->
<import resource="hibernate-context.xml" />
Run Code Online (Sandbox Code Playgroud)

我的hibernate-context.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/jdbc 
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/util 
            http://www.springframework.org/schema/util/spring-util-3.1.xsd
            http://www.springframework.org/schema/mvc …
Run Code Online (Sandbox Code Playgroud)

xml spring xsd hibernate

1
推荐指数
1
解决办法
1万
查看次数

在Hibernate中过滤

我有一个非常简单的一对多关系,并希望使用in子句过滤多边(集合).我无法让过滤器工作.Hibernate都抱怨过滤器参数是未定义的(当使用Set或Integer作为类型时)或者说传入的值是错误的类型(当使用int参数类型时)

关系:类别有很多测试用例,测试用例只有一个类别

POJO#1

@Entity
@Table(name = "CATEGORY")
public class Category
{
    @Id
    @Column(name = "CATEGORYID")
    private int ID;

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

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "CATEGORYID")
    @Filter(name = "TEST_RUN_ID_FILTER")
    private Collection<SimpleTestCase> testCases;
}
Run Code Online (Sandbox Code Playgroud)

Pojo#2

@Entity
@Table(name = "TESTCASE_NEW")
@FilterDef(name = "TEST_RUN_ID_FILTER", defaultCondition = "TESTRUNID in (:IDS)", parameters = { @ParamDef(name = "IDS", type = "Integer") })
public class SimpleTestCase
{
    @Id
    @Column(name = "TESTCASEID")
    private int ID;

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

    @Column(name = "STATUS") …
Run Code Online (Sandbox Code Playgroud)

annotations hibernate filter one-to-many

1
推荐指数
1
解决办法
5553
查看次数

理解注释和JPA(休眠)

有一个结构.我想以这种方式链接这三个实体:公司应该包含id,公司名称和部门列表,每个部门都有一个Worker列表,id和部门名称.每个工人都有名字,身份证.

+Company
-int companyId
-String companyName
-Set<Department> listOfDepartments = new HashSet<Department>();

+Department
-int departmentId
-String departmentName
-Set<Worker> listOfWorkers = new HashSet<Worker>();

+Worker
-int workerId
-String workerName
Run Code Online (Sandbox Code Playgroud)

我尝试与一对多和多对一建立连接,但是没有成功.

Сompany

@Entity
@Table(name="Company")
public class Company {

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idCompany;
private String companyName;

@OneToMany(mappedBy = "company")
private Set<Department> listOfDepartments = new HashSet<Department>();
Run Code Online (Sandbox Code Playgroud)

部门

@Entity
public class Department {

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idDepartment;
private String departmentName;

@ManyToOne
@JoinColumn(name="idCompany")
private Company company;

@OneToMany(mappedBy = "department")
private Set<Worker> listOfWorkers …
Run Code Online (Sandbox Code Playgroud)

java hibernate

1
推荐指数
1
解决办法
4662
查看次数

获取计划又名.取组也称.QueryDSL中的实体图

我无法在QueryDSL中找到任何实现获取计划的方法,我尝试了很多.你能给我任何提示吗?另外,你知道更好的方法来选择要获取哪些字段以及在不同情况下懒散加载哪些字段?我使用批量提取,因此我不能使用JOIN FETCH.

java jpa querydsl

1
推荐指数
1
解决办法
2367
查看次数