0

我有 2 个带 JPA2 注释的类和一个为它们工作的 JUnit 测试,但我决定添加独特的约束,这会导致 createManagerFactory 失败。

以下是课程:

@Entity 
@NamedQuery(
    name="XmlConversion.Queries.XmlByPdfAndPdf2Xml",
    query="SELECT c FROM XmlConversion c WHERE c.pdf = :pdfname AND c.pdf2xml_sha1 = :pdf2xml") 
@Table(name = "xml_conversion", uniqueConstraints={
       @UniqueConstraint(columnNames={"pdf_id", "pdf2xml_sha1"})})
public class XmlConversion implements java.io.Serializable {

private Integer id;
private Pdf pdf;
private Long xmlOutputSize;
private String pdf2xml_sha1;
private Integer durationMillisec;
private Date createdAt;

public XmlConversion() {
}

public XmlConversion(Pdf pdf, String pdf2xml_sha1_sourceforge) {
    this.pdf = pdf;
    this.pdf2xml_sha1 = pdf2xml_sha1_sourceforge;
}

public XmlConversion(Pdf pdf, Long xmlOutputSize, String gitVersion,
        Integer durationMillisec) {
    this.pdf = pdf;
    this.xmlOutputSize = xmlOutputSize;
    this.pdf2xml_sha1 = gitVersion;
    this.durationMillisec = durationMillisec;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

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

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "pdf_id", nullable = false)
public Pdf getPdf() {
    return this.pdf;
}

public void setPdf(Pdf pdf) {
    this.pdf = pdf;
}

@Column(name = "xml_output_size")
public Long getXmlOutputSize() {
    return this.xmlOutputSize;
}

public void setXmlOutputSize(Long xmlOutputSize) {
    this.xmlOutputSize = xmlOutputSize;
}

@Column(name = "pdf2xml_version", nullable = false, length = 45)
public String getPdf2xml_sha1() {
    return this.pdf2xml_sha1;
}

public void setPdf2xml_sha1(String gitVersion) {
    this.pdf2xml_sha1 = gitVersion;
}

@Column(name = "duration_millisec")
public Integer getDurationMillisec() {
    return this.durationMillisec;
}

@Column(name = "created_at", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreatedAt() {
    return this.createdAt;
}

public void setCreatedAt(Date createdAt) {
    //this.createdAt = createdAt;
    //shall be set at the DB level
}

public void setDurationMillisec(Integer durationMillisec) {
    this.durationMillisec = durationMillisec;
}

}




@Entity
@NamedQuery(
    name="Pdf.Queries.PdfByNameAndSize",
    query="SELECT c FROM Pdf c WHERE c.name = :pdfname AND c.size = :pdfsize"
 )
@Table(name = "pdf", uniqueConstraints={
       @UniqueConstraint(columnNames={"name", "size"})})
public class Pdf implements java.io.Serializable {

@Column(nullable=false)
private Integer id;
@Column(nullable=false)
private String name;
@Column(nullable=false)
private Long size;
private Set<XmlConversion> xmlConversions = new HashSet<XmlConversion>(0);

public Pdf() {
}

public Pdf(String name, Long size) {
    this.name = name;
    this.size = size;
}

public Pdf(String name, Long size, Set<XmlConversion> xmlConversions) {
    this.name = name;
    this.size = size;
    this.xmlConversions = xmlConversions;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

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

@Column(name = "name", nullable = false, length = 245)
public String getName() {
    return this.name;
}

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

@Column(name = "size", nullable = false, length = 16777215)
public Long getSize() {
    return this.size;
}

public void setSize(Long size) {
    this.size = size;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "pdf")
public Set<XmlConversion> getXmlConversions() {
    return this.xmlConversions;
}

public void setXmlConversions(Set<XmlConversion> xmlConversions) {
    this.xmlConversions = xmlConversions;
}
  }

这是 JUnit 测试:

public class PersistenceTest {

private static EntityManagerFactory emf;
private static EntityManager em;
private static String randomPDFname;
private static String randomGITversion;
private static long sysTime = 0;

@BeforeClass
public static void createEntityManagerFactory() {
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "hibernate URL is "+System.getProperty("hurl"));        
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "the path to pdf2xml is "+System.getProperty("pdf2xml"));           
    emf = Persistence.createEntityManagerFactory("pdfEx");
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "PersistenceTest: EM factory created!");        
    randomPDFname = UUID.randomUUID().toString()+".pdf";
    randomGITversion = UUID.randomUUID().toString()+".git";
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "PersistenceTest: randomPDFname = "+randomPDFname);         
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "PersistenceTest: randomGITversion = "+randomGITversion);           
    sysTime = Math.round(System.currentTimeMillis()/((10^3)*3600));//systime in hours, rather than millisecs
}

@Before
public void beginTransaction() {
    em = (EntityManager) Persistence.createEntityManagerFactory("pdfEx").createEntityManager();
    em.getTransaction().begin();
}

@After
public void rollbackTransaction() {

    if (em.getTransaction().isActive())
        em.getTransaction().rollback();

    if (em.isOpen())
        em.close();
}

@AfterClass
public static void closeEntityManagerFactory() {
    emf.close();
}

@Test
public void dbTest() {
    //fail("Not yet implemented");
    Pdf testPdf = new Pdf();
    testPdf.setName(randomPDFname);
    testPdf.setSize(sysTime);       
    //check that testPDF is, indeed, not yet in the DB:
    Query getPDF = em.createNamedQuery("Pdf.Queries.PdfByNameAndSize");
    getPDF.setParameter("pdfname", testPdf.getName());
    getPDF.setParameter("pdfsize", testPdf.getSize());
    List foundPDFs = getPDF.getResultList();
    assertTrue("Random PDF "+randomPDFname+" is already in the DB", foundPDFs == null || foundPDFs.size() == 0 );
    //persist testPdf in the DB
    em.persist(testPdf);
    //em.flush();
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "Persisted testPdf");
    //retrieve testPdf from the DB
    Pdf thePDF = (Pdf) getPDF.getSingleResult();//trying to re-run the query
    //and use it as a reference in a new XmlConversion
    XmlConversion testXml = new XmlConversion();
    testXml.setPdf2xml_sha1(randomGITversion);
    testXml.setPdf(thePDF);
    testXml.setXmlOutputSize(sysTime);
    //verify there is no such XmlConversion
    Query getXML = em.createNamedQuery("XmlConversion.Queries.XmlByPdfAndPdf2Xml");
    getXML.setParameter("pdfname", testXml.getPdf());
    getXML.setParameter("pdf2xml", testXml.getPdf2xml_sha1());
    List foundXMLs = getXML.getResultList();
    assertTrue("XmlConversion is already in the DB", foundXMLs == null || foundXMLs.size() == 0 );
    //store XmlConversion in the DB
    em.persist(testXml);
    //em.flush();
    //retrieve XmlConversion from the DB
    foundXMLs = getXML.getResultList();
    assertTrue("XmlConversion is not in the DB", foundXMLs.size() == 1);
    Logger.getLogger(PdfConverter.class.getName()).log(Level.INFO, "PersistenceTest successful!");         
}
}

这是persistence.xml:

<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pdfEx" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <!-->validation-mode>AUTO</validation-mode-->
    <class>iw.pdfEx.persistence.Pdf</class>
    <class>iw.pdfEx.persistence.XmlConversion</class>
    <properties>
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.connection.username" value="icite"/>
        <property name="hibernate.connection.password" value="${hpass}"/>
        <property name="hibernate.connection.url" value="${hurl}"/>
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
    </properties>
</persistence-unit>

这是错误消息:

Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 1.933 sec <<< FAILURE! iw.pdfEx.PersistenceTest  Time elapsed: 1.926 sec  <<< ERROR! java.lang.NullPointerException: null
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
at java.util.TimSort.sort(TimSort.java:189)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at iw.pdfEx.PersistenceTest.createEntityManagerFactory(PersistenceTest.java:43) iw.pdfEx.PersistenceTest  Time elapsed: 1.933 sec  <<< ERROR! java.lang.NullPointerException: null
at iw.pdfEx.PersistenceTest.closeEntityManagerFactory(PersistenceTest.java:70)

这是测试的输出:

Aug 04, 2013 10:38:09 PM iw.pdfEx.PersistenceTest createEntityManagerFactory 
INFO: hibernate URL is jdbc:mysql://localhost:8600/icite Aug 04, 2013 10:38:09 PM iw.pdfEx.PersistenceTest createEntityManagerFactory 
INFO: the path to pdf2xml is /home/nikolay/Documents/invoiceFairy/pdf2xml/pdftoxml.linux64.exe.1.2_7 Aug 04, 2013 10:38:09 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Aug 04, 2013 10:38:09 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.3.Final}
Aug 04, 2013 10:38:09 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 04, 2013 10:38:09 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 04, 2013 10:38:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!) Aug 04, 2013 10:38:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 Aug 04, 2013 10:38:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true Aug 04, 2013 10:38:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:8600/icite] Aug 04, 2013 10:38:10 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=icite, password=****, autocommit=true, release_mode=auto} Aug 04, 2013 10:38:10 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect

你能说出什么是错的吗?如前所述,测试一直有效,直到我添加了唯一约束,并且我认为我在任何地方重命名了两个实体之间的连接列 (pdf_id)。任何帮助表示赞赏。

4

1 回答 1

5

定义唯一约束如下

@UniqueConstraint(columnNames={"pdf_id", "pdf2xml_sha1"})})

失败,因为没有持久性属性映射到名为 的列pdf2xml_sha1。该名称有一个持久属性,但它似乎映射到pdf2xml_version列:

@Column(name = "pdf2xml_version", nullable = false, length = 45)
public String getPdf2xml_sha1() {
    return this.pdf2xml_sha1;
}

解决方案是在两者pdf2xml_sha1中使用一个。pdf2xml_version

于 2013-08-05T18:33:05.827 回答