org.hibernate.LazyInitializationException could not initialize proxy – no Session

Error LazyInitializationException ­čÖé

Bismillah

q> Ini coding header


package com.saifiahmada.spring.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class HdrTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "HDR_ID" , length=36)
private String hdrId;

@Temporal(TemporalType.TIMESTAMP)
private Date tglTest;

@Column(length = 20)
private String username;

@OneToMany(cascade={CascadeType.ALL})
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

public String getHdrId() {
return hdrId;
}

public void setHdrId(String hdrId) {
this.hdrId = hdrId;
}

public Date getTglTest() {
return tglTest;
}

public void setTglTest(Date tglTest) {
this.tglTest = tglTest;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public List<DtlTest> getDtlTests() {
return dtlTests;
}

public void setDtlTests(List<DtlTest> dtlTests) {
this.dtlTests = dtlTests;
}
}

q> Ini coding detail


package com.saifiahmada.spring.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class DtlTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "DTL_ID" , length=36)
private String dtlId;

@Column(name="ID_SOAL", length=36)
private String idSoal;

@Column(length=1)
private String jawabanSiswa;

@ManyToOne
@JoinColumn(name="hdr_id")
private HdrTest hdrTest;

public DtlTest() {

}

public String getDtlId() {
return dtlId;
}

public void setDtlId(String dtlId) {
this.dtlId = dtlId;
}

public String getIdSoal() {
return idSoal;
}

public void setIdSoal(String idSoal) {
this.idSoal = idSoal;
}

public String getJawabanSiswa() {
return jawabanSiswa;
}

public void setJawabanSiswa(String jawabanSiswa) {
this.jawabanSiswa = jawabanSiswa;
}

public HdrTest getHdrTest() {
return hdrTest;
}

public void setHdrTest(HdrTest hdrTest) {
this.hdrTest = hdrTest;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dtlId == null) ? 0 : dtlId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DtlTest other = (DtlTest) obj;
if (dtlId == null) {
if (other.dtlId != null)
return false;
} else if (!dtlId.equals(other.dtlId))
return false;
return true;
}

@Override
public String toString() {
return "DtlTest [dtlId=" + dtlId + "]";
}

}

q> Ketika coba mengambil data dengan coding ini


package com.saifiahmada.spring;

import java.util.List;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;

import com.saifiahmada.spring.domain.DtlTest;
import com.saifiahmada.spring.domain.HdrTest;
import com.saifiahmada.spring.repository.HdrTestRepository;

@Configurable
@EnableAutoConfiguration
public class OfflineTest {

public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(OfflineTest.class, args);

HdrTestRepository repo = (HdrTestRepository) ctx.getBean("hdrTestRepository");

List<HdrTest> list = repo.findAll();
for (HdrTest hdr : list) {
System.out.println("" + hdr.getHdrId());
System.out.println("" + hdr.getUsername());
System.out.println("" + hdr.getTglTest());
for (DtlTest dtl : hdr.getDtlTests()) {
System.out.println("" + dtl.getDtlId());
System.out.println("" + dtl.getIdSoal());
System.out.println("" + dtl.getJawabanSiswa());
}
}

}
}

q> Muncul error ini

Exception in thread “main” org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.saifiahmada.spring.domain.HdrTest.dtlTests, could not initialize proxy – no Session

q> Coba kita tambahkan code ini pada header

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)

q> Sehingga coding untuk OneToMany pada header seperti ini :

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

q> Berhasil mengambil seluruh header beserta detailnya ­čÖé

Alhamdulillah

Advertisements

@lob menghasilkan longtext mysql

Ternyata @lob menghasilkan longtext pada mysql

Bismillah

Test coding ini ­čÖé

private static final long serialVersionUID = 1L;
@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(length=64)
private String id;

@Lob
private String teks;

private String pilihanA;

private String pilihanB;

private String pilihanC;

private String pilihanD;

private String pilihanE;
@Column(length=1)
private String jawaban;
@Column(length=25)
private String tipe;

q> Ketika di-build ( / + running code)Menghasilkan table seperti ini :

testcode

Alhamdulillah

server side validator menggunakan hibernate validator

Server side validator, melanjutkan tulisan sebelumnya, aplikasi menggunakan framework spring mvc, spring data jpa dan hibernate entity manager

Bismillah

q> Melanjutkan tulisan ini :
https://saifiahmada.wordpress.com/2014/12/25/membuat-crud-sederhana-spring-mvc/

q> Langkah-langkah praktek :

1. tambahkan mvc namespace pada dispatcher-servlet
2. tambahkan tag <mvc:annotaion-driven /> pada dispatcher-servlet
3. tambahkan dependency hibernate validator 5.1.0 final pada pom.xml
4. tambahkan annotation pada domain object
5. tambahkan @Valid dan BindingResult pada parameter method add pada controller
6. tambahkan tag <form:errors> pada JSP
7. testing hasil

q> – – – mulai – – –

1. tambahkan mvc namespace pada dispatcher-servlet

Selection_637

2. tambahkan tag <mvc:annotaion-driven /> pada dispatcher-servlet

<mvc:annotaion-driven />

3. tambahkan dependency hibernate validator 5.1.0 final pada pom.xml

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>

4. tambahkan annotation pada domain object

@Id
 @GeneratedValue
 private Integer id;
 
 @Size(min=3, message="minimal 3 karakter!")
 @NotBlank
 private String nama;
 
 @Size(min=5, message="minimal 5 karakter!")
 @NotBlank
 private String alamat;
 @Size(min=11, message="minimal 11 karakter!")
 @NotBlank
 private String noHp;

5. tambahkan @Valid dan BindingResult pada parameter method add pada controller

@RequestMapping(value = "/add", method=RequestMethod.POST)
public String add(Model model, @Valid @ModelAttribute("customer") Customer customer, BindingResult result){

logger.info("method add");

if (result.hasErrors()) {
model.addAttribute("customers", customerService.findAll());
return "customer";
}
customerService.save(customer);
return "redirect:/customer/awal.html?success=true";
}

6. tambahkan tag <form:errors> pada JSP

<form:errors path="nama" />
<form:errors path="alamat" />
<form:errors path="noHp" />

7. testing hasil

Selection_636

Ketika tombol simpan ditekan, maka akan muncul pesan bahwa minimal karakter harus dipenuhi

Alhamdulillah

membuat crud sederhana spring mvc

Create Read Update Delete menggunakan spring mvc, spring data jpa, hibernate entity manager, tiles, mysql

Bismillah

q> Melanjutkan tulisan sebelumnya :
https://saifiahmada.wordpress.com/2014/12/13/menambah-menu-stok/

q> Langkah-langkah praktek :
1. Buat bean entity Customer
2. Buat interface CustomerRepositroy
3. Buat class CustomerService
4. Tambahkan definition pada general.xml
5. Tambahkan menu pada classic.jsp
6. Buat file customer.jsp pada /WEB-INF/jsp/
7. Tambahkan class controller CustomerController

1. Buat bean entity Customer

package com.saifiahmada.maven.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Customer {

	@Id
	@GeneratedValue
	private Integer id;

	private String nama;

	private String alamat;

	private String noHp;

	public Integer getId() {
		return id;
	}

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

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}

	public String getAlamat() {
		return alamat;
	}

	public void setAlamat(String alamat) {
		this.alamat = alamat;
	}

	public String getNoHp() {
		return noHp;
	}

	public void setNoHp(String noHp) {
		this.noHp = noHp;
	}

}

2. Buat interface CustomerRepositroy

package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.Customer;

public interface CustomerRepository extends JpaRepository<Customer, Integer> {

}

3. Buat class CustomerService

package com.saifiahmada.maven.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.saifiahmada.maven.entity.Customer;
import com.saifiahmada.maven.repository.CustomerRepository;

@Service
public class CustomerService {

	@Autowired
	private CustomerRepository customerRepository;

	public void save(Customer customer) {
		customerRepository.save(customer);
	}

	public List<Customer> findAll() {
		return customerRepository.findAll();
	}

}

4. Tambahkan definition pada general.xml

	<definition name="customer" extends="common">
		<put-attribute name="title" value="Customer" />
		<put-attribute name="body" value="/WEB-INF/jsp/customer.jsp" />
		<put-attribute name="current" value="customer" />
	</definition>

5. Tambahkan menu pada classic.jsp

<li class="${current == 'customers' ? 'active' : '' }">
<a href="/customer/awal.html">Customer</a></li>

6. Buat file customer.jsp pada /WEB-INF/jsp/

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<form:form commandName="customer" action="/customer/add.html"
	cssClass="form-horizontal">

	<c:if test="${ ! empty customer.nama }">
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">Id</label>
			<div class="col-sm-10">
				<form:input path="id" cssClass="form-control" readonly="true" disabled="true" />
				<form:hidden path="id"/>
			</div>
		</div>

	</c:if>

	<div class="form-group">
		<label for="nama" class="col-sm-2 control-label">Nama</label>
		<div class="col-sm-10">
			<form:input path="nama" cssClass="form-control" />
		</div>
	</div>

	<div class="form-group">
		<label for="alamat" class="col-sm-2 control-label">Alamat</label>
		<div class="col-sm-10">
			<form:input path="alamat" cssClass="form-control" />
		</div>
	</div>

	<div class="form-group">
		<label for="noHp" class="col-sm-2 control-label">No HP</label>
		<div class="col-sm-10">
			<form:input path="noHp" cssClass="form-control" />
		</div>
	</div>

	<input type="submit" value="Simpan" class="btn btn-success" />
	<a href="/customer/awal.html" class="btn btn-success">Reset</a>

</form:form>

<br />

<table class="table table-bordered table-hover table-striped">
	<thead>
		<tr>
			<th>Nama</th>
			<th>Alamat</th>
			<th>No. HP</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${customers}" var="c">
			<tr>
				<td>${c.nama }</td>
				<td>${c.alamat }</td>
				<td>${c.noHp }</td>
				<td><a href="/customer/edit/${c.id}.html">Edit</a></td>
				<td><a href="/customer/delete/${c.id}.html">Delete</a></td>
			</tr>
		</c:forEach>
	</tbody>
</table>

7. Tambahkan class controller CustomerController

package com.saifiahmada.maven.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.saifiahmada.maven.entity.Customer;
import com.saifiahmada.maven.service.CustomerService;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

	@Autowired
	private CustomerService customerService;

	@ModelAttribute("customer")
	public Customer getCustomer(){
		return new Customer();
	}

	@RequestMapping(value="/awal")
	public String awal(Model model){
		model.addAttribute("customer", new Customer());
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

	@RequestMapping(value = "/add", method=RequestMethod.POST)
	public String add(@ModelAttribute("customer") Customer customer){
		customerService.save(customer);
		return "redirect:/customer/awal.html";
	}

	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable("id") Integer id, Model model){
		Customer customer = customerService.findOne(id);
		model.addAttribute("customer", customer);
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id, Model model){
		customerService.delete(id);
		model.addAttribute("customers", customerService.findAll());
		return "customer";
	}

}

q> Jalankan jetty untuk melihat hasilnya

q> Awal menu Customer di-klik
Selection_632

q> Edit salah satu data, kemudian tekan tombol simpan

Selection_633

q> Masukkan data baru

Selection_634

q> Data tersimpan

Selection_635

Alhamdulillah

membuat modal bootstrap untuk form simpan

Membuat form simpan untuk data barang

Bismillah

Melanjutkan tulisan ini :
https://saifiahmada.wordpress.com/2014/12/13/css-menu-aktif-ketika-pilih-menu/

1. buka getbootstrap.com > menu JavaScript > link Modal

2. copy paste pada example Modal ke file baranglist.jsp

3. tambahkan method consctuct BarangController

4. Edit dan tambahkan script pada baranglist.jsp

5. Tambahkan controller untuk simpan pada BarangController

6. Menambahkan pesan/notifikasi data berhasil disimpan

7. Testing hasil

q> – – – mulai – – –

1. buka getbootstrap.com > menu JavaScript > link Modal

Selection_623

2. copy paste pada example Modal ke file baranglist.jsp

3. tambahkan method consctuct BarangController

@ModelAttribute("barang")
public Barang constructBarang(){
return new Barang();
}

4. Edit dan tambahkan script pada baranglist.jsp

file baranglist.jsp sekarang seperti ini :


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<c:if test="${param.success eq true }">
<div class="alert alert-success">Data berhasil disimpan !</div>
</c:if>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal"
data-target="#myModal">Tambah Barang</button>

<form:form commandName="barang" cssClass="form-horizontal">

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Tambah Barang</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="kode" class="col-sm-2 control-label">Kode</label>
<div class="col-sm-10">
<form:input path="kode" cssClass="form-control" />
</div>
</div>

<div class="form-group">
<label for="nama" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<form:input path="nama" cssClass="form-control" />
</div>
</div>

<div class="form-group">
<label for="harga" class="col-sm-2 control-label">Harga</label>
<div class="col-sm-10">
<form:input path="harga" cssClass="form-control" />
</div>
</div>

</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<input type="submit" class="btn btn-primary" value="Simpan" />
</div>
</div>
</div>
</div>
</form:form>

<br />
<br />

<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>Kode</td>
<td>Nama Barang</td>
<td>Harga</td>
</tr>
</thead>
<tbody>
<c:forEach items="${barangs}" var="barang">
<tr>
<td>${barang.kode}</td>
<td>${barang.nama}</td>
<td>${barang.harga}</td>
</tr>
</c:forEach>
</tbody>
</table>

5. Tambahkan controller untuk simpan pada BarangController

@RequestMapping(value="/barang/list", method=RequestMethod.POST)
public String simpan(@ModelAttribute("barang") Barang barang){
System.out.println("simpan");
barangService.save(barang);
return "redirect:/barang/list.html?success=true";
}

6. Menambahkan pesan/notifikasi data berhasil disimpan

<c:if test="${param.success eq true }">
<div class="alert alert-success">Data berhasil disimpan !</div>
</c:if>

7. Testing hasil

tampilan awal ketika menu Barang di-klik

Selection_624

klik menu Tambah Barang, kemudian isi data barang dan klik tombol Simpan

Selection_625

 

ketika tombol Simpan diklik maka ada notifikasi data berhasil disimpan :

Selection_626

Alhamdulillah