您使用什么样的替代策略来避免LazyLoadExceptions?
我确实理解在视图中打开会话有以下问题:
但是,如果您知道您的应用程序在单个虚拟机上运行,为什么不通过在视图策略中使用开放会话来减轻您的痛苦?
对于我们的新产品重新设计,我们正在从Java中选择最佳框架.考虑到模型的数据库不可知方法,我们正在研究Struts + Spring与iBATIS或Hibernate之间的选择.请提供最好的建议,因为两者都提供持久性.
我一直患有臭名昭着的hibernate异常
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Run Code Online (Sandbox Code Playgroud)
现在社区正在欢呼
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
说它解决了问题,但小心使用它.
他们的意思是谨慎使用它?这个属性实际上做了什么?
请给我任何见解.提前致谢.
我有一个模型有一个相当大的子实体图和hibernate最终制作了大约9个语句懒洋洋地获取所需的所有数据但大约4级深度我得到一个"无法初始化代理 - 没有会话"错误,我是不知道为什么.
调节器
@Transactional(readOnly = true)
@RequestMapping(value = "/v2/plans", method = RequestMethod.GET)
public @ResponseBody List<PlanPresenter> show(HttpServletRequest request) throws Exception {
List<PlanPresenter> planPresenters = new ArrayList<>();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Plan> planQuery = criteriaBuilder.createQuery(Plan.class);
Root<Plan> root = planQuery.from(Plan.class);
if (request.getParameter("region") != null || request.getParameter("group") != null) {
List<Predicate> criteria = new ArrayList<Predicate>();
if (request.getParameter("region") != null) {
criteria.add(criteriaBuilder.equal(root.get(Plan_.region), request.getParameter("region")));
}
if (request.getParameter("group") != null) {
criteria.add(criteriaBuilder.equal(root.get(Plan_.groupCode), request.getParameter("group")));
criteria.add(root.get(Plan_.planSetId).in(groupPlanSetIds));
} else {
criteria.add(root.get(Plan_.planSetId).in(currentPlanSetIds));
}
Query query = entityManager.createQuery(planQuery.where(criteriaBuilder.and(criteria.toArray(new Predicate[]{}))));
for (Plan …Run Code Online (Sandbox Code Playgroud) 我尝试用java和jpa做函数searchBook.我有2个课程,分别是媒体和书.本书扩展了媒体.我将数据保存在不同的表中.我尝试从下面的查询中选择数据:
TypedQuery<Media> query = em.createQuery(
"SELECT m.title, b.isbn, b.authors"
+ " FROM Book b, Media m" + " WHERE b.isbn = :isbn"
+ " OR lower(m.title) LIKE :title"
+ " OR b.authors LIKE :authors", Media.class);
query.setParameter("isbn", book.getisbn());
query.setParameter("title", "%" + book.getTitle().toLowerCase()
+ "%");
query.setParameter("authors", "%" + book.getAuthors() + "%");
bookList = query.getResultList();
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误:
java.lang.IllegalArgumentException:无法为具有多个返回的查询创建TypedQuery
这是我第一次使用JPA.我找不到错误.
我有两个类Participant和TimeWindow。多个参与者可以注册多个 TimeWindow,因此存在 ManyToMany 关系
@Entity
@Table
public class Participant {
@Id
@SequenceGenerator(
name = "participant_sequence",
sequenceName = "particant_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "participant_sequence"
)
private Long id;
private String name;
private String number;
private String details;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "ParticipantCreneaux")
private Collection<TimeWindow> registeredTimeWindow;
public Participant() {
}
public Participant(String nom, String num, String details) {
this.name = nom;
this.number = num;
this.details = details;
this.registeredTimeWindow = new ArrayList<>(); …Run Code Online (Sandbox Code Playgroud) 对数据库有以下查询:
Session session = EmployeesDAO.getSessionFactory().getCurrentSession();
List<Employee> employees = new ArrayList<Employee>();
try {
session.beginTransaction();
String hqlQuery = "from Employee emp "
+ "left join fetch emp.employeesOffices employeesOffice "
+ "left join fetch employeesOffice.office employeesOfficeOffice "
+ "left join fetch employeesOfficeOffice.company "
+ "left join fetch emp.address empAddress "
+ "left join fetch empAddress.city empAddressCity "
+ "left join fetch empAddressCity.country";
Query empQuery = session.createQuery(hqlQuery);
empQuery.setMaxResults(maxResult);
employees = (List<Employee>) empQuery.list();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
在获取employee.address.street,employee.address.houseNumber或employee.address.city时,它失败并出现异常:
org.hibernate.LazyInitializationException: could …Run Code Online (Sandbox Code Playgroud) 我们正在加载spring/hibernate/c3p0应用程序.当我将c3p0 maxPoolSize减少到远远低于并发用户数时,我们的应用程序就会挂起.日志中没有错误消息,但它也没有继续前进.
我希望应用程序放慢速度,但不要完全停止.
这是我们的c3p0配置:
<bean id="coreDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${core.jdbc.driver}"
p:jdbcUrl="${core.jdbc.url}"
p:user="${core.jdbc.user}"
p:acquireIncrement="5"
p:acquireRetryAttempts="10"
p:acquireRetryDelay="5000"
p:initialPoolSize="52"
p:maxIdleTime="3600"
p:maxIdleTimeExcessConnections="300"
p:minPoolSize="52"
p:maxPoolSize="125"
p:numHelperThreads="6"
p:unreturnedConnectionTimeout="0">
<property name="password">
<bean class="com.docfinity.util.encryption.SpringStringDecrypter"
p:decryptFlag="${core.jdbc.decryptPasswordFlag}"
p:encryptedString="${core.jdbc.password}" />
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
如果我扔了160个用户,这将锁定.
我尝试将unreturnedConnectionTimeout设置为正值(120秒),并查看我们的应用程序中显示的堆栈跟踪.堆栈跟踪来自我们的应用程序中的各种不同方法.这并不是说我们可以指出一种方法,并说它正在泄漏连接.
任何帮助调试此问题的人都将非常感激.
我正在使用Hibernate 5.1.0.Final和ehcache以及Spring 3.2.11.RELEASE.我@Cacheable在其中一个中设置了以下注释DAO:
@Override
@Cacheable(value = "main")
public Item findItemById(String id)
{
return entityManager.find(Item.class, id);
}
Run Code Online (Sandbox Code Playgroud)
返回的项目有许多关联,其中一些是懒惰的.例如,它(最终)引用该字段:
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "product_category", joinColumns = { @JoinColumn(name = "PRODUCT_ID") }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID") })
private List<Category> categories;
Run Code Online (Sandbox Code Playgroud)
我注意到在我标记的一个方法中@Transactional,当从二级缓存中检索到上述方法时,我在尝试迭代categories字段时得到以下异常:
@Transactional(readOnly=true)
public UserContentDto getContent(String itemId, String pageNumber) throws IOException
{
Item Item = contentDao.findItemById(ItemId);
…
// Below line causes a “LazyInitializationException” exception
for (Category category : item.getParent().getProduct().getCategories())
{
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪是:
16:29:42,557 INFO [org.directwebremoting.log.accessLog] (ajp-/127.0.0.1:8009-18) …Run Code Online (Sandbox Code Playgroud) 我有一种情况,我必须在两个选项之间做出选择,但我不清楚这些选项之间有什么区别。如果有人可以向我解释我应该选择哪一个以及为什么,我将非常感激。长话短说,我有一个简单的 JPA 实体(Kotlin 语言):
@Entity
@Table(name = "account")
data class AccountEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long,
var balance: Int,
@ManyToOne
var accountType: AccountTypeEntity
)
Run Code Online (Sandbox Code Playgroud)
在业务逻辑层,我想要一种通过其 accountId 更新帐户余额的方法。基本上我需要通过 id 加载帐户实体,然后设置新的余额,最后使用 Hibernate 提供的保存方法。但我也发现如果我的方法将用@transactional 注释,我不需要以显式形式调用 save 方法。所以从那时起我有两个选择
第一
fun updateAccountBalance(id: Long, balance: Int) {
val account = accountRepository.findById(id).orElseThrow { RuntimeException("No account with id=$id found") }
account.balance = balance
accountRepository.save(account)
}
Run Code Online (Sandbox Code Playgroud)
第二个
@Transactional
fun updateAccountBalance(id: Long, balance: Int) {
val account = accountRepository.findById(id).orElseThrow { RuntimeException("No account with id=$id found") }
account.balance = …Run Code Online (Sandbox Code Playgroud) 我在 Java 企业应用程序中工作。该应用程序具有后端的休眠框架。由于最近应用程序的变化,一些代码消耗了来自 weblogic 服务器的所有 JDBC 连接池。
应用程序连接是在代码中处理的属性,对于每个线程,我们使用 threadlocal 类创建每个会话。所以创建连接没有问题。该应用程序已使用超过 5 年。
我们怀疑最近的代码更改导致了这个主要问题。最后我们决定使用分析器工具来调查这个问题。
在此之前,我将回顾最近的代码更改,那么我在回顾时需要记住的 hibernate 关键点是什么?
这是非常危急/严重的情况。所以建议我一些提示来解决这个问题..
谢谢
我正在使用JPA2.1和hibernate 4.3.8,我已经配置了presistence.xml以允许延迟加载
我已经添加了
<property name="hibernate.enable_lazy_load_no_trans" value="true" />
Run Code Online (Sandbox Code Playgroud)
进入属性部分
但我仍然得到LazyInitializtionException,有什么问题?
当我将println()放在DAO方法中时,程序在我调用update方法时有效.
@Override
public Post getPostById(int id) {
Session session = DatabaseConnection.connect().openSession();
Post post = (Post) session.load(Post.class, new Integer(id));
System.out.println("debug " + post);
session.close();
return post;
}
Run Code Online (Sandbox Code Playgroud)
当我不这样做时,它给了我一个错误
@Override
public Post getPostById(int id) {
Session session = DatabaseConnection.connect().openSession();
Post post = (Post) session.load(Post.class, new Integer(id));
session.close();
return post;
}
Run Code Online (Sandbox Code Playgroud)
这是错误消息:
SEVERE: Invalid property 'account' of bean class [com.personal.pojo.Post_$$_jvsta3d_0]: Getter for property 'account' threw exception; nested exception is java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property 'account' of bean class [com.personal.pojo.Post_$$_jvsta3d_0]: Getter for property 'account' threw …Run Code Online (Sandbox Code Playgroud) hibernate ×11
java ×10
jpa ×4
spring ×4
c3p0 ×2
lazy-loading ×2
persistence ×2
spring-boot ×2
ehcache ×1
frameworks ×1
ibatis ×1
kotlin ×1
postgresql ×1
sql ×1