gpt4 book ai didi

java - jpa + hibernate + 独立

转载 作者:行者123 更新时间:2023-12-01 13:19:23 30 4
gpt4 key购买 nike

我无法理解为什么这种关系没有被持久化,并且程序不会正常退出,但在 Eclipse 中继续运行。

下面是我的代码,排除了包名:

主要:

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;

import PanelDao;
import Panel;
import Panelbinary;


public class PanelService {
static byte[] file;
/**
* @param args
*/
public static void main(String[] args) {
try {
// TODO Auto-generated method stub
InputStream in = new Object().getClass().getClassLoader().getSystemResourceAsStream("Astrology.zip");
BufferedInputStream bin = new BufferedInputStream(in);
byte[] ba = new byte[1024];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int n = -1;
while(-1 != (n = bin.read(ba))) {
bout.write(ba, 0, n);
}
file = bout.toByteArray();
System.out.println("Astrology.zip bytes:" + file.length);

if(file.length > 0) {
Panel p = new PanelService().uploadAstrologoyPanel();
System.out.println("panel id=" + p.getId());
System.out.println("panelbinaryid=" + p.getPanelbinaries().get(0).getId());

}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public Panel uploadAstrologoyPanel() {
Panel p = new Panel();
PanelDao pd = new PanelDao();

Date d = new Date();
p.setPanelcategoryid(new BigDecimal(1));//books
p.setPanelbinarytypeid(new BigDecimal(5));//json
p.setDescription("Astrology");
p.setDisplayname("Astrology");
p.setFilterid(new BigDecimal(1));//all devices
p.setLabel("Astrology");
p.setPackagename("com.jio.panel.astrology");
p.setCreated(d);
p.setModified(d);
pd.create(p);

Panelbinary pb = new Panelbinary();
pb.setActive(new BigDecimal(0));
pb.setArtifact(file);
pb.setArtifactsize(new BigDecimal(file.length));
pb.setUserversion("1");
pb.setWidget(new BigDecimal(0));
pb.setCreated(d);
pb.setModified(d);
pb.setIncversion(new BigDecimal(1));
p.addPanelbinary(pb);
//pb.setPanel(p);

p = pd.update(p);
pd.entityManager.close();
return p;

}

}

PanelBinary 实体

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

import javax.persistence.*;


import org.hibernate.annotations.ForeignKey;


/**
* The persistent class for the PANELBINARY_ database table.
*
*/
@Entity
@Table(
name = "PANELBINARY_",
uniqueConstraints = { @UniqueConstraint(
name = "PB_PID_IV_UK",
columnNames = { "PANELID", "INCVERSION" }),
@UniqueConstraint(
name = "PB_PID_UV_UK",
columnNames = { "PANELID", "USERVERSION" }) })
@SequenceGenerator(
name = "PANELBINARYSEQ",
sequenceName = "PANELBINARYSEQ",
allocationSize = 1,
initialValue = 1)
@SuppressWarnings("serial")
public class Panelbinary implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(generator = "PANELBINARYSEQ", strategy = GenerationType.SEQUENCE)
private long id;

@Column(name = "ACTIVE", nullable = false)
private BigDecimal active;

@Lob
@Basic(optional = false, fetch = FetchType.LAZY)
@Column(name = "ARTIFACT", nullable = false) private byte[] artifact;

@Column(name = "ARTIFACTSIZE", nullable = true)
private BigDecimal artifactsize;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED", nullable = false)
private Date created;

@Lob
private byte[] icon;

private BigDecimal iconsize;

@Column(name = "INCVERSION", nullable = false)
private BigDecimal incversion;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "MODIFIED", nullable = false)
private Date modified;

@Lob
private byte[] thumbnail;

private BigDecimal thumbnailsize;


@Column(name = "USERVERSION", nullable = false, length = 50)
private String userversion;

@Column(name = "WIDGET", nullable = true)
private BigDecimal widget;

//bi-directional many-to-one association to Panel
@ManyToOne(optional = false)
@JoinColumn(name = "PANELID", nullable = false)
@ForeignKey(name = "PB_PID_FK")
private Panel panel;

public Panelbinary() {
}

public long getId() {
return this.id;
}

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

public BigDecimal getActive() {
return this.active;
}

public void setActive(BigDecimal active) {
this.active = active;
}

public byte[] getArtifact() {
return this.artifact;
}

public void setArtifact(byte[] artifact) {
this.artifact = artifact;
}

public BigDecimal getArtifactsize() {
return this.artifactsize;
}

public void setArtifactsize(BigDecimal artifactsize) {
this.artifactsize = artifactsize;
}

public Date getCreated() {
return this.created;
}

public void setCreated(Date created) {
this.created = created;
}

public byte[] getIcon() {
return this.icon;
}

public void setIcon(byte[] icon) {
this.icon = icon;
}

public BigDecimal getIconsize() {
return this.iconsize;
}

public void setIconsize(BigDecimal iconsize) {
this.iconsize = iconsize;
}

public BigDecimal getIncversion() {
return this.incversion;
}

public void setIncversion(BigDecimal incversion) {
this.incversion = incversion;
}

public Date getModified() {
return this.modified;
}

public void setModified(Date modified) {
this.modified = modified;
}

public byte[] getThumbnail() {
return this.thumbnail;
}

public void setThumbnail(byte[] thumbnail) {
this.thumbnail = thumbnail;
}

public BigDecimal getThumbnailsize() {
return this.thumbnailsize;
}

public void setThumbnailsize(BigDecimal thumbnailsize) {
this.thumbnailsize = thumbnailsize;
}

public String getUserversion() {
return this.userversion;
}

public void setUserversion(String userversion) {
this.userversion = userversion;
}

public BigDecimal getWidget() {
return this.widget;
}

public void setWidget(BigDecimal widget) {
this.widget = widget;
}

public Panel getPanel() {
return this.panel;
}

public void setPanel(Panel panel) {
this.panel = panel;
}

}

面板实体

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.*;


/**
* The persistent class for the PANEL_ database table.
*
*/
@Entity
@Table(
name = "PANEL_",
uniqueConstraints = @UniqueConstraint(
name = "P_LABEL_PACKAGENAME_UK",
columnNames = { "LABEL", "PACKAGENAME" }))
@SequenceGenerator(
name = "PANELSEQ",
sequenceName = "PANELSEQ",
allocationSize = 1,
initialValue = 1)
@SuppressWarnings("serial")
public class Panel implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(generator = "PANELSEQ", strategy = GenerationType.SEQUENCE)
private long id;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED", nullable = false)
private Date created;

@Column(name = "DESCRIPTION", length = 250)
private String description;

@Column(name = "DISPLAYNAME", length = 64)
private String displayname;

private BigDecimal filterid;

private BigDecimal initialstateid;

@Column(name = "LABEL", nullable = false, length = 100)
private String label;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "MODIFIED", nullable = false)
private Date modified;

@Column(name = "PACKAGENAME", nullable = false, length = 250)
private String packagename;

private BigDecimal panelbinarytypeid;

private BigDecimal panelcategoryid;

private BigDecimal panelorder;

//bi-directional many-to-one association to Panelbinary
@OneToMany(mappedBy="panel")
private List<Panelbinary> panelbinaries;

public Panel() {
}

public long getId() {
return this.id;
}

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

public Date getCreated() {
return this.created;
}

public void setCreated(Date created) {
this.created = created;
}

public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

public String getDisplayname() {
return this.displayname;
}

public void setDisplayname(String displayname) {
this.displayname = displayname;
}

public BigDecimal getFilterid() {
return this.filterid;
}

public void setFilterid(BigDecimal filterid) {
this.filterid = filterid;
}

public BigDecimal getInitialstateid() {
return this.initialstateid;
}

public void setInitialstateid(BigDecimal initialstateid) {
this.initialstateid = initialstateid;
}

public String getLabel() {
return this.label;
}

public void setLabel(String label) {
this.label = label;
}

public Date getModified() {
return this.modified;
}

public void setModified(Date modified) {
this.modified = modified;
}

public String getPackagename() {
return this.packagename;
}

public void setPackagename(String packagename) {
this.packagename = packagename;
}

public BigDecimal getPanelbinarytypeid() {
return this.panelbinarytypeid;
}

public void setPanelbinarytypeid(BigDecimal panelbinarytypeid) {
this.panelbinarytypeid = panelbinarytypeid;
}

public BigDecimal getPanelcategoryid() {
return this.panelcategoryid;
}

public void setPanelcategoryid(BigDecimal panelcategoryid) {
this.panelcategoryid = panelcategoryid;
}

public BigDecimal getPanelorder() {
return this.panelorder;
}

public void setPanelorder(BigDecimal panelorder) {
this.panelorder = panelorder;
}

public List<Panelbinary> getPanelbinaries() {
if(null == panelbinaries) {
panelbinaries = new ArrayList<Panelbinary>();
}
return this.panelbinaries;
}

public void setPanelbinaries(List<Panelbinary> panelbinaries) {
this.panelbinaries = panelbinaries;
}

public Panelbinary addPanelbinary(Panelbinary panelbinary) {
getPanelbinaries().add(panelbinary);
panelbinary.setPanel(this);

return panelbinary;
}

public Panelbinary removePanelbinary(Panelbinary panelbinary) {
getPanelbinaries().remove(panelbinary);
panelbinary.setPanel(null);

return panelbinary;
}

}

DAO

import Panel;

public class PanelDao extends GenericDaoJpaImpl<Panel, Integer> {

@Override
public Panel create(Panel t) {

try {
entityManager.getTransaction().begin();
super.create(t);
entityManager.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
entityManager.getTransaction().rollback();
}
return t;
}



@Override
public Panel update(Panel t) {
try {
entityManager.getTransaction().begin();
super.update(t);
entityManager.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();

entityManager.getTransaction().rollback();
}
return t;
}

@Override
public void delete(Panel t) {
try {
entityManager.getTransaction().begin();
super.delete(t);
entityManager.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();

entityManager.getTransaction().rollback();
}
}
}

DAO super 类

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

public class GenericDaoJpaImpl<T, PK extends Serializable>
implements GenericDao<T, PK> {
static {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("dev2db");
entityManager = factory.createEntityManager();
}
protected Class<T> entityClass;

@PersistenceContext
public static EntityManager entityManager;

public GenericDaoJpaImpl() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass()
.getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass
.getActualTypeArguments()[0];
}

@Override
public T create(T t) {
this.entityManager.persist(t);
return t;
}

@Override
public T read(PK id) {
return this.entityManager.find(entityClass, id);
}

@Override
public T update(T t) {
return this.entityManager.merge(t);
}

@Override
public void delete(T t) {
t = this.entityManager.merge(t);
this.entityManager.remove(t);
}
}

super dao接口(interface)

import java.io.Serializable;

public interface GenericDao<T, PK extends Serializable> {
T create(T t);
T read(PK id);
T update(T t);
void delete(T t);
}

持久性.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="dev2db" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate" />

<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@host:1521:xxxx" />
<property name="javax.persistence.jdbc.user" value="xxxx" />
<property name="javax.persistence.jdbc.password" value="xxxx" />
</properties>
</persistence-unit>
</persistence>

日志:

Astrology.zip bytes:267
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: dev2db
...]
Mar 04, 2014 1:01:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Mar 04, 2014 1:01:10 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 04, 2014 1:01:10 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 04, 2014 1:01:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:@host:port:sid]
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=prodm6_fix, password=****}
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mar 04, 2014 1:01:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Mar 04, 2014 1:01:11 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: PRODM6_FIX.PANELBINARY_
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [icon, thumbnailsize, modified, id, userversion, artifact, thumbnail, created, iconsize, panelid, active, incversion, artifactsize, widget]
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: xxxx.PANEL_
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [panelorder, id, initialstateid, created, panelcategoryid, description, packagename, label, panelbinarytypeid, filterid, modified, displayname]
panel id=13
panelbinaryid=0

我想要得到的是 panel 和 panelbinaryid 都有有效值。我没有看到 panelbinary 被持久保存在数据库中。

即使我关闭实体管理器,插入面板后程序也不会终止。

如果能够通过几行代码和注释轻松添加容器管理的事务,而不是采用全新的方式,那就太好了。

问候,

米滕。

最佳答案

1 - 关于持久性问题,这是因为您的关联由 PanelBinary 管理(由您的属性 @OneToMany(mappedBy="panel") 定义),并且没有向下级联关系。

要使其正常工作,您需要:

  • 使用 PanelBinary 对象中的面板对象设置面板属性(您已执行此操作并进行了注释!)
  • 用级联属性定义一对多关系

    @OneToMany(cascade=ALL, mappedBy="panel")
    private List<Panelbinary> panelbinaries;

2 - 要使用注释“轻松”设置事务行为,您应该查看 Spring 文档:

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

基本上,您需要定义一个 Spring 配置文件来定义数据源、事务管理和启用事务注释。还可以在这里找到教程:

http://techannotation.wordpress.com/2012/05/29/5-minutes-with-jpa-transaction/

3 - 没有关于程序未完成的线索..最后的日志显示它到达了主方法的末尾..

关于java - jpa + hibernate + 独立,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22165971/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com