#Query keep pulling null from database - mysql

I am currently having what I'd like to call as Code Block (Writer block but with coding). I have tried to check many times and make sure that everything is in the proper place but it keeps getting me a null despite the data that I ask in the #Query is exist.
This is the #Query that I currently have,
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
String findAllDenda(String x,String y,String z);
My expected output from there is a collection of "denda" from the table of "data_transaksi_model" which has the specific "tanggal", "name", and "masa_pajak" from that table. I have double checked the table that is created within the database and it has the same name as to what I inquire there,
As you can see, the table name is matchup and the name of the column name that has the name of what I want in my query is also match up. Just to make sure, I also check the structure of the database and it is indeed a string, also the same with others.
The table is the byproduct of the model from my Spring Boot's project that I have made.
#Entity
public class DataTransaksiModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "tanggal")
private String tanggal;
#NotNull
#Column(name = "no_kohir")
private String noKohir;
#NotNull
#Column(name = "no_urut")
private String noUrut;
#NotNull
#Column(name = "nama_wp")
private String namaWP;
#NotNull
#Column(name = "jam")
private String jam;
#NotNull
#Column(name = "nop")
private String nop;
#NotNull
#Column(name = "denda")
private String denda;
#NotNull
#Column(name = "jumlah_setoran")
private String jumlahSetoran;
#NotNull
#Column(name = "luas_tanah")
private String luasTanah;
#NotNull
#Column(name = "luas_bangunan")
private String luasBangunan;
#NotNull
#Column(name = "kecamatan")
private String kecamatan;
#NotNull
#Column(name = "kelurahan")
private String kelurahan;
#NotNull
#Column(name = "masa_pajak")
private String masaPajak;
#NotNull
#Column(name = "lokasi")
private String lokasi;
#NotNull
#Column(name = "pokok")
private String pokok;
#NotNull
#Column(name = "cabang")
private String cabang;
#NotNull
#Column(name = "User")
private String user;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getNoKohir() {
return noKohir;
}
public void setNoKohir(String noKohir) {
this.noKohir = noKohir;
}
public String getNoUrut() {
return noUrut;
}
public void setNoUrut(String noUrut) {
this.noUrut = noUrut;
}
public String getNamaWP() {
return namaWP;
}
public void setNamaWP(String namaWP) {
this.namaWP = namaWP;
}
public String getJam() {
return jam;
}
public void setJam(String jam) {
this.jam = jam;
}
public String getNop() {
return nop;
}
public void setNop(String nop) {
this.nop = nop;
}
public String getDenda() {
return denda;
}
public void setDenda(String denda) {
this.denda = denda;
}
public String getJumlahSetoran() {
return jumlahSetoran;
}
public void setJumlahSetoran(String jumlahSetoran) {
this.jumlahSetoran = jumlahSetoran;
}
public String getLuasTanah() {
return luasTanah;
}
public void setLuasTanah(String luasTanah) {
this.luasTanah = luasTanah;
}
public String getLuasBangunan() {
return luasBangunan;
}
public void setLuasBangunan(String luasBangunan) {
this.luasBangunan = luasBangunan;
}
public String getKecamatan() {
return kecamatan;
}
public void setKecamatan(String kecamatan) {
this.kecamatan = kecamatan;
}
public String getKelurahan() {
return kelurahan;
}
public void setKelurahan(String kelurahan) {
this.kelurahan = kelurahan;
}
public String getMasaPajak() {
return masaPajak;
}
public void setMasaPajak(String masaPajak) {
this.masaPajak = masaPajak;
}
public String getLokasi() {
return lokasi;
}
public void setLokasi(String lokasi) {
this.lokasi = lokasi;
}
public String getPokok() {
return pokok;
}
public void setPokok(String pokok) {
this.pokok = pokok;
}
public String getCabang() {
return cabang;
}
public void setCabang(String cabang) {
this.cabang = cabang;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
With that finished, I insert a data dummy into the database as the following.
Therefore, I tried to put the input of tanggal with "1170130", nama_wp with "SURATNO" and masa_pajak with "2016". However, I keep getting null instead of "9.166" in the collection. Where did I do wrong? I am using XAMPP, MySQL, and Spring Boot for this project.
/EDIT: I tried it manually in my XAMPP with SELECT denda FROM data_transaksi_modelWHERE nama_wp="SURATNO" AND masa_pajak="2014" AND tanggal="1170130" and it actually gives me a return
However, when I do it in my spring boot project it still return null.
//Edit2: I am using IntelliJ as my IDE and there is a warning (not an error) within the #Query annotation. It is said that "No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (alt+enter)" there is also a warning that said, "SQL dialect is not configured". If that is the source of the problem, how to fix it?
///edit3: I tried to fix around the query and it doesn't show the result that I wanted. This is the service that I am using for the repository
#Autowired
DataTransaksiDb dataTransaksiDb;
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
and this is the controller where I am using the service. The controller is using a multipart file where the data is taken out from the CSV that is uploaded where within the CSV has the table that is the same as the database.
#PostMapping("/uploadFile")
public static void uploadFile(#RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
if (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
InputStreamReader input = new InputStreamReader(file.getInputStream());
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
for (CSVRecord record : csvParser) {
String nama = record.get("nama_wp");
String masa = record.get("masa_pajak");
String tanggal = record.get("tanggal");
String denda = record.get("denda");
String jumlahSetoran = record.get("jumlah_setoran");
String pokok = record.get("pokok");
String luasTanah = record.get("luas_tanah");
String luasBangunan = record.get("luas_bangunan");
try {
System.err.println(tanggal + "\n" + nama + "\n" + masa);
List<String> results = rekonsiliasiService.getDenda(tanggal, nama, masa);
System.err.println("results " + results);
} catch (NullPointerException e) {
System.err.println(e);
}
}
response.sendRedirect("/rekonsiliasi");
} else {
response.sendRedirect("/rekonsiliasi");
}
}
Whatever the result of the input that I get, it keep getting catches by the nullpointerexception
////EDIT4:
I tried debugging it and from my controller, I tried to do System.err.println(rekonsiliasiService.getDenda(tanggal,nama,masa)); and it keep me getting a NullPointerException. Then I tried to see if the problem is the input of the parameter itself within the service
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak);
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
It never reached to the System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak); within my Service layer.

try this :
#Query(value = "select d.denda from DataTransaksiModel d WHERE d.tanggal=:x AND d.namaWP = :y AND d.masaPajak=:z")
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);
if it didn't work try this :
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);

Related

How to solve HHH000346 Error using hibernate 5 and mysql?

I'm studying restful service and views.
Regarding it, I use mysql and hibernate 5.
My data tables are two and have reference relation.
The problem occurs when I update the primary key.
When I add new one then update existing data in another table (they have reference relation), HHH000346: Error during managed flush occurs.
I already search on google, but I couldn't find the answer.
This is my Entity classes.
#Entity
#Table(name = "users")
#EntityListeners(AuditingEntityListener.class)
public class User {
private long serial;
private String username;
private String password;
public User() {
}
public User(long serial, String username, String password) {
setSerial(serial);
setUsername(username);
setPassword(password);
}
#Column(name = "serial", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
public long getSerial() {
return serial;
}
public void setSerial(long serial) {
this.serial = serial;
}
#Id
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "serial: " + this.serial + ", username: " + this.username + ", password: " + this.password;
}
}
Entity
#Table(name = "sites")
#EntityListeners(AuditingEntityListener.class)
#IdClass(Site.class)
public class Site implements Serializable{
#ManyToOne
#JoinColumn(name="username",foreignKey=#ForeignKey(name="username"))
private String username;
private String siteURL;
#Id
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Id
public String getSiteURL() {
return siteURL;
}
public void setSiteURL(String siteName) {
this.siteURL = siteName;
}
}
And this is class had problem.
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private SiteRepository siteRepository;
private CryptoUtil passwordEncoder = new CryptoUtil();
...
#PutMapping("/users/{username}")
public User updateUser(#PathVariable(value = "username") String username, #Valid #RequestBody User userDetails)
throws ResourceNotFoundException {
User user = userRepository.findById(username)
.orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + username));
List<Site> sites = siteRepository.findByUsername(user.getUsername());
userDetails.setPassword(passwordEncoder.encryptSHA256(userDetails.getPassword()));
final User updateUser = userRepository.save(userDetails);
for (Site site : sites)
{
site.setUsername(userDetails.getUsername());
site = siteRepository.save(site);
}
userRepository.delete(user);
return updateUser;
}
....
}
The for-each statement occurs error.
PLEASE HELP ME
Why did you do this?
#ManyToOne
#JoinColumn(name="username",foreignKey=#ForeignKey(name="username"))
private String username;
It should be:
#ManyToOne
#JoinColumn(name="username",foreignKey=#ForeignKey(name="username"))
private User user;
I'll also suggest you to use the primary key as foreign key.
And you can't have multiple #Id in an entity.

How to use native query with spring repo mapped to custom object?

I have table t1:
id | title
1 | title1
2 | title2
and I have the following spring repo method:
#Query(nativeQuery = true, value = "select id, title from t1")
public List<T1> getAll();
The custom class is:
public class T1 {
#JsonProperty("id")
private Integer id;
#JsonProperty("title")
private String title;
public T1(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I'm expecting to get the following json response:
{[{"id":1, "title":"titl1"}, {"id":2, "title":"titl2"}]}
However i'm getting this one:
[[1,"title1"],[2,"title2"]]
I'm using #RestController
#RequestMapping(method = RequestMethod.GET, value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntityTestResponse> test() {
List<T1> list = testRepository.getAll();
TestResponse response = new TestResponse(list);
return new ResponseEntity<TestResponse>(response, HttpStatus.OK);
}
TestResponse class is:
public class TestResponse implements Serializable {
private TreeSet<T1> list = new TreeSet<>();
public TestResponse(TreeSet<T1> list) {
this.list = list;
}
....
Can you help with that?
This response is classic Java List, if you need it as JSON object, you have to use for example GSON and then you should write something like this:
sonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
System.out.println(gson.toJson(YOUR_LIST_OF_T1));
Here are examples (included that was i wrote) and here is GitHub repo.
You can do it manually by overrite toString() method in T1 class if u need it in specific signature, and u didn't got any API doing what you want.
So if u try some thing like that
List<T1> list = testRepository.getAll();
StringBuilder strBuilder = new StringBuilder();
for(T1 t : list){
strBuilder.append(t.toString() + ", ");
}
String result = "";
if(strBuilder.length()!=0){
result = "{[" + strBuilder.substring(0, strBuilder.length()-2) + "]}";
}
System.out.println(result);
and class should overrite toString() method
class T1{
#JsonProperty("id")
private Integer id;
#JsonProperty("title")
private String title;
public T1(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "{\"id:\"" + id + ", \"title:\"" + title + "}";
}
}
Also if you want to use pure java standard library you can do it like next code but you will need to download javax.json-xxxx.jar(for example >> javax.json-1.0.4.jar) (that include providers or the implementation) to your library project path
But this next code will generate something like that
[{"id":1,"title":"Title1"},{"id":2,"title":"Title2"},{"id":3,"title":"Title3"}]
List<T1> list = testRepository.getAll();
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for(T1 t : list) {
jsonArray.add(Json.createObjectBuilder()
.add("id", t.getId())
.add("title", t.getTitle()));
}
System.out.println(jsonArray.build());

Dropwizard Hibernate Configuration

I am new to Dropwizard and so far everything was going well till I started messing with Hibernate and MySQL. My problem is: Hibernate won't create tables and consequently no columns in my DB.
The only warning I get when running my jar file is:
org.hibernate.cfg.environment hibernate.properties not found
But do I need it at all? As I am having all configuration and mapping already.
Here is my application class:
public class LibraryApplication extends Application<LibraryConfiguration> {
public static void main(String[] args) throws Exception {
new LibraryApplication().run(args);
}
#Override
public String getName() {
return "hello backend";
}
private final HibernateBundle<LibraryConfiguration> hibernate = new HibernateBundle<LibraryConfiguration>(Book.class){ //more entities can be added separated with a coma
public DataSourceFactory getDataSourceFactory(LibraryConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
#Override
public void initialize(Bootstrap<LibraryConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/webapp", "/", "index.html", "static"));
bootstrap.addBundle(hibernate);
}
#Override
public void run(LibraryConfiguration configuration,
Environment environment) {
final BookDAO dao = new BookDAO(hibernate.getSessionFactory());
final TestResource resource = new TestResource(
configuration.getTemplate(), configuration.getDefaultName());
final TemplateHealthCheck healthCheck = new TemplateHealthCheck(
configuration.getTemplate());
environment.healthChecks().register("template", healthCheck); //register the health check
environment.jersey().register(resource); //register the resource class
environment.jersey().register(new BookResource(dao));
}
}
YAML file:
server:
type: simple
rootPath: '/api/*'
applicationContextPath: /
connector:
type: http
port: 8080
template: Hello, %s!
defaultName: back-end
database:
# the name of your JDBC driver
driverClass: com.mysql.jdbc.Driver
# the JDBC URL
url: jdbc:mysql://localhost:3306/books
# the username
user: root
# the password
password: root
# any properties specific to your JDBC driver:
properties:
charSet: UTF-8
hibernate.dialect: org.hibernate.dialect.MySQLDialect #org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto: create
Configurtion class:
public class LibraryConfiguration extends Configuration{
#Valid
#NotNull
#JsonProperty
private DataSourceFactory database = new DataSourceFactory();
#JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
#NotEmpty
private String template;
#NotEmpty
private String defaultName = "";
#JsonProperty
public String getTemplate() {
return template;
}
#JsonProperty
public void setTemplate(String template) {
this.template = template;
}
#JsonProperty
public String getDefaultName() {
return defaultName;
}
#JsonProperty
public void setDefaultName(String name) {
this.defaultName = name;
}
}
and my entity:
#Entity
#Table(name = "book")
#NamedQueries({
#NamedQuery(
name = "library.core.Book.findAll",
query = "SELECT b FROM book b"
)
})
public class Book{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Long id;
#Column(name = "title")
#NotNull
private String title;
#Column(name = "author")
#NotNull
private String author;
#Column(name = "date")
private long date;
#Column(name = "description")
private String description;
#Column(name = "image")
private String image;
public Book(String title, String author){
this.title = title;
this.author = author;
}
#JsonProperty
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#JsonProperty
public Long getId() {
return id;
}
#JsonProperty
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#JsonProperty
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
#JsonProperty
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonProperty
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public void setId(Long id) {
this.id = id;
}
}
I have already been to many tutorials but none of them really explains how to configure hibernate. Thank you in advance.
I have finally solved this problem, which was not a big deal actually. Just a small mistake as it was expected.
My problem was a Book class, IDE automatically imported the java library called Book in the LibraryApplication class, so DB was not mapping it.
On the other hand, in the Book class the named query should be as follows:
#NamedQuery(
name = "library.core.Book.findAll",
query = "SELECT b FROM Book b"
)
My mistake: I was writing Book with small letter.

Excluding properties from JSON processing in Struts2

I have the following (full) entity class.
public class StateTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "state_id", nullable = false)
private Long stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<UserTable> userTableSet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<City> citySet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<Inquiry> inquirySet;
#OneToMany(mappedBy = "shippingState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
#OneToMany(mappedBy = "paymentState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet1;
#JoinColumn(name = "country_id", referencedColumnName = "country_id")
#ManyToOne(fetch = FetchType.LAZY)
private Country countryId;
public StateTable() {
}
public StateTable(Long stateId) {
this.stateId = stateId;
}
public Long getStateId() {
return stateId;
}
public void setStateId(Long stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
#XmlTransient
public Set<UserTable> getUserTableSet() {
return userTableSet;
}
public void setUserTableSet(Set<UserTable> userTableSet) {
this.userTableSet = userTableSet;
}
#XmlTransient
public Set<City> getCitySet() {
return citySet;
}
public void setCitySet(Set<City> citySet) {
this.citySet = citySet;
}
#XmlTransient
public Set<Inquiry> getInquirySet() {
return inquirySet;
}
public void setInquirySet(Set<Inquiry> inquirySet) {
this.inquirySet = inquirySet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet1() {
return orderTableSet1;
}
public void setOrderTableSet1(Set<OrderTable> orderTableSet1) {
this.orderTableSet1 = orderTableSet1;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stateId != null ? stateId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StateTable)) {
return false;
}
StateTable other = (StateTable) object;
if ((this.stateId == null && other.stateId != null) || (this.stateId != null && !this.stateId.equals(other.stateId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.StateTable[ stateId=" + stateId + " ]";
}
}
I need only two properties from this class as a JSON response namely, stateId and stateName. The rest of the properties must be ignored from being processed/serialized by JSON.
I have tried to set json.excludeProperties to the json interceptor as follows.
#Namespace("/admin_side")
#ResultPath("/WEB-INF/content")
#ParentPackage(value="json-default")
public final class StateListAction extends ActionSupport implements Serializable, ValidationAware
{
#Autowired
private final transient SharableService sharableService=null;
private static final long serialVersionUID = 1L;
private Long id;
List<StateTable>stateTables=new ArrayList<StateTable>();
public StateListAction() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JSON(name="stateTables")
public List<StateTable> getStateTables() {
return stateTables;
}
public void setStateTables(List<StateTable> stateTables) {
this.stateTables = stateTables;
}
#Action(value = "PopulateStateList",
results = {
#Result(type="json", name=ActionSupport.SUCCESS, params={"json.enableSMD", "true", "json.enableGZIP", "true", "json.excludeNullProperties", "true", "json.root", "stateTables", "json.excludeProperties", "userTableSet, citySet, inquirySet, orderTableSet, orderTableSet1, countryId", "validation.validateAnnotatedMethodOnly", "true"})})
public String populateStateList() throws Exception
{
System.out.println("countryId = "+id);
stateTables=sharableService.findStatesByCountryId(id);
return ActionSupport.SUCCESS;
}
}
The remaining properties are expected to be ignored after doing this but it doesn't seem to work. Number of SQL statements associated with all of the entity classes are generated which in turn causes other severe errors to occur like,
org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public"
What am I missing here? How to ignore all the properties except stateId and stateName?
I'm using Struts2-json-plugin-2.3.16.
You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"contentType", "text/javascript", "includeProperties",
"stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"})

Adding data to multiple tables using Spring forms in Spring MVC

I have the following database schema and I need to add data to all three tables using a single view http://i.stack.imgur.com/3HXhC.png (Due to stackoverflow rules, I cannot link the image directly).
What I hope to achieve, is to create an order, have it given an Workshop order id, and have it linked to LineItems which will let the user specify the quantity of items from the Inventory table to be added to the order.
I can create a workshop order in my database, and create a lineitem with the workshop orders id, and add the id and quantity from an inventory item into the lineitem table, and then use the attached code to display each lineitem orderline, with the total amount of items, which item is in the order, total price, customer name etc.
How do I go about creating a view that will let me create an order this way? The flow I imagine is:
Create workshop order -> add line items from inventory -> save the order.
Having worked on Spring and Hibernate for only a couple of weeks, I have not really figured out a smart approach to solve this, but hopefully someone in here has. By all means, feel free to criticize my database scheme, my classes and anything else. It may be a stupid design, not well suited for an actual production system.
I have attached my primary classes involved in this.
LineItems.java
#Entity
#Table(name = "LINE_ITEMS")
#AssociationOverrides({
#AssociationOverride(name = "pk.inventory",
joinColumns = #JoinColumn(name = "INVENTORY_Id")),
#AssociationOverride(name = "pk.workshop",
joinColumns = #JoinColumn(name = "WORKSHOP_ORDERS_Id"))
})
public class LineItems implements Serializable {
private static final long serialVersionUID = 5703588914404465647L;
#EmbeddedId
private LineItemsPK pk = new LineItemsPK();
private int quantity;
public LineItems() {
}
public LineItemsPK getPK() {
return pk;
}
public void setPK(LineItemsPK pk) {
this.pk = pk;
}
#Column(name = "WORKSHOP_ORDERS_Id", nullable=false, updatable=false,
insertable=false)
public Long getWorkshopOrdersId() {
return getPK().getWorkshop().getId();
}
#Column(name = "Id")
#JoinColumn(name="INVENTORY_Id", nullable=false, updatable=false, insertable=false)
public Long getInventoryId() {
return getPK().getInventory().getId();
}
#ManyToOne
public Workshop getWorkshop() {
return getPK().getWorkshop();
}
public void setWorkshop(Workshop workshop) {
getPK().setWorkshop(workshop);
}
#ManyToOne
#JoinColumn(name = "INVENTORY_Id")
public Inventory getInventory() {
return getPK().getInventory();
}
public void setInventory(Inventory inventory) {
getPK().setInventory(inventory);
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LineItems that = (LineItems) o;
if (getPK() != null ? !getPK().equals(that.getPK())
: that.getPK() != null) {
return false;
}
return true;
}
public int hashCode() {
return (getPK() != null ? getPK().hashCode() : 0);
}
}
LineItemsPK.java
#Embeddable
public class LineItemsPK implements Serializable {
private static final long serialVersionUID = -4285130025882317338L;
#ManyToOne
private Inventory inventory;
#ManyToOne
private Workshop workshop;
public Workshop getWorkshop() {
return workshop;
}
public void setWorkshop(Workshop workshop) {
this.workshop = workshop;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
#Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
LineItemsPK that = (LineItemsPK) o;
if(workshop != null ? !workshop.equals(that.workshop) : that.workshop != null) {
return false;
}
if(inventory != null ? !inventory.equals(that.inventory) : that.inventory != null) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result;
result = (workshop != null ? workshop.hashCode() : 0);
result = 31 * result + (inventory != null ? inventory.hashCode() : 0);
return result;
}
}
Workshop.java
#Entity
#Table(name = "WORKSHOP_ORDERS")
public class Workshop implements Serializable {
private static final long serialVersionUID = -8106245965993313684L;
public Long id;
public Long inventoryItemId;
public String workshopService;
public String workshopNotes;
public Long customersId;
public Long paymentId;
private Customer customer;
private Payment payment;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Workshop() {
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment, Set<LineItems> lineItems) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.workshop", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#ManyToOne
#JoinColumn(name="CUSTOMERS_Id", nullable = false, insertable = false, updatable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(final Customer customer) {
this.customer = customer;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="PAYMENT_Id", insertable = false, updatable = false, nullable = false)
public Payment getPayment() {
return payment;
}
public void setPayment(final Payment payment) {
this.payment = payment;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", nullable = false)
public Long getId() {
return id;
}
#Column(name = "InventoryItemId")
public Long getInventoryItemId() {
return inventoryItemId;
}
#Column(name = "WorkshopService")
public String getWorkshopService() {
return workshopService;
}
#Column(name = "WorkshopNotes")
public String getWorkshopNotes() {
return workshopNotes;
}
#Column(name = "CUSTOMERS_Id")
public Long getCustomersId() {
return customersId;
}
#Column(name = "PAYMENT_Id")
public Long getPaymentId() {
return paymentId;
}
public void setId(Long id) {
this.id = id;
}
public void setInventoryItemId(Long inventoryItemId) {
this.inventoryItemId = inventoryItemId;
}
public void setWorkshopService(String workshopService) {
this.workshopService = workshopService;
}
public void setWorkshopNotes(String workshopNotes) {
this.workshopNotes = workshopNotes;
}
public void setCustomersId(Long customersId) {
this.customersId = customersId;
}
public void setPaymentId(Long paymentId) {
this.paymentId = paymentId;
}
public String toString() {
return "Customer id: " + this.customersId + "Notes: " + workshopNotes;
}
}
Inventory.java
#Entity
#Table(name = "INVENTORY")
public class Inventory implements Serializable {
private static final long serialVersionUID = -8907719450013387551L;
private Long id;
private String itemName;
private String itemVendorName;
private Long itemInventoryStatus;
private Double itemBuyPrice;
private Double itemSellPrice;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Inventory() {
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice, Set<LineItems> lineItems) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.inventory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#Id
#Column(name = "Id", nullable = false)
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return this.id;
}
#Column(name = "ItemName")
public String getItemName() {
return this.itemName;
}
#Column(name = "ItemVendorName")
public String getItemVendorName() {
return this.itemVendorName;
}
#Column(name = "ItemInventoryStatus")
public Long getItemInventoryStatus() {
return this.itemInventoryStatus;
}
#Column(name = "ItemBuyPrice")
public Double getItemBuyPrice() {
return this.itemBuyPrice;
}
#Column(name = "ItemSellPrice")
public Double getItemSellPrice() {
return this.itemSellPrice;
}
public void setId(Long id) {
this.id = id;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public void setItemVendorName(String itemVendorName) {
this.itemVendorName = itemVendorName;
}
public void setItemInventoryStatus(Long itemInventoryStatus) {
this.itemInventoryStatus = itemInventoryStatus;
}
public void setItemBuyPrice(Double itemBuyPrice) {
this.itemBuyPrice = itemBuyPrice;
}
public void setItemSellPrice(Double itemSellPrice) {
this.itemSellPrice = itemSellPrice;
}
public String toString() {
return "Item id:" + this.id + " ItemName: " + this.itemName +
" ItemInventoryStatus: " + this.itemInventoryStatus +
" ItemBuyPrice: " + this.itemBuyPrice + " ItemSellPrice " + this.itemSellPrice;
}
}
This isn't really a question as it is more of a "how would I do this"
What have you tried already?
Where are you running into trouble?
etc.
Your view logic should not be coupled with your domain layer, what I mean is, you write your forms to be as usable as possible yet, still get the information you need. Once you post the information to the backing Controller, you do the required business logic in order to line up how the entities persist, etc.
Continuing this line of thinking, your controller should only be worried about web layer exceptions, and passing information on to the Business / Service Layer. From the Business / Service layer you execute required logic, and pass on to the Domain / Repository layer. This gives a clear separation of concerns allowing for easier testing.