30 December 2019

JPA: Composite Primary Key with Foreign Keys



 
Entity for the ProductSales Table:

package com.example.model;

import javax.persistence.*;

@Entity
@IdClass(ProductSalesPK.class)
public class ProductSales {

 @Column(name = "QUANTITY")
 private int quantity_sold;

 @Id
 @ManyToOne
 @JoinColumn(name = "sales_id")
 private Sales sales;

 @Id
 @ManyToOne
 @JoinColumn(name = "product_id")
 private Product product;

 public ProductSales() {
 }

 public ProductSales(Sales sales, Product product, int quantity_sold) {
  this.sales = sales;
  this.product = product;
  this.quantity_sold = quantity_sold;
 }

 public Product getProduct() {
  return product;
 }

 public Sales getSales() {
  return sales;
 }

 public void setProduct(Product product) {
  this.product = product;
 }

 public void setSales(Sales sales) {
  this.sales = sales;
 }

 public int getQuantity_sold() {
  return quantity_sold;
 }

 public void setQuantity_sold(int quantity_sold) {
  this.quantity_sold = quantity_sold;
 }
}

ProductSalesPK Id class:

package com.example.model;

import java.util.Objects;

public class ProductSalesPK {
    private int sales;
    private String product;

 public ProductSalesPK(int sales_id, String product_id) {
  this.sales = sales_id;
  this.product = product_id;
 }

 @Override
 public int hashCode() {
  int hash = 5;
  hash = 83 * hash + this.sales;
  hash = 83 * hash + Objects.hashCode(this.product);
  return hash;
 }

 @Override
 public boolean equals(Object obj) {
  if (obj == null) {
   return false;
  }
  if (getClass() != obj.getClass()) {
   return false;
  }
  final ProductSalesPK other = (ProductSalesPK) obj;
  if (this.sales != other.sales) {
   return false;
  }
  if (!Objects.equals(this.product, other.product)) {
   return false;
  }
  return true;
 } 
}
Entity class fpor Product:

package com.example.model;
package com.example.model;

import java.util.Objects;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
public class Product {
 @NotNull(message="product id not null") @Size (min = 1,message="product id not empty") 
 @Id
    private String product_id; 
 @NotNull(message="product name not null") @Size (min = 10,message="product name length at least 10")
    private String prod_name;
 @Min(value=5, message="price >= {value}")
    private double price;
    private String prod_desc;

 public Product() {
 }

  
    public Product(String id, String name, double price, String description) {
        this.product_id = id;
        this.prod_name = name;
        this.price = price;
        this.prod_desc = description;
    }

    public String getId() {
        return product_id;
    }

    public String getName() {
        return prod_name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getDescription() {
        return prod_desc;
    }

    public void setDescription(String description) {
        this.prod_desc = description;
    }
    
    @Override
    public String toString() {
        String s = String.format("Product id: %s\n"
        + "Name: %s\n"
        + "Description: %s\n"
        + "Price: $%.2f", product_id, prod_name, prod_desc, price);
        return s;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + Objects.hashCode(this.product_id);
        hash = 97 * hash + Objects.hashCode(this.prod_name);
        hash = 97 * hash + (int) (Double.doubleToLongBits(this.price) ^ (Double.doubleToLongBits(this.price) >>> 32));
        hash = 97 * hash + Objects.hashCode(this.prod_desc);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Product other = (Product) obj;
        if (!Objects.equals(this.product_id, other.product_id)) {
            return false;
        }
        if (!Objects.equals(this.prod_name, other.prod_name)) {
            return false;
        }
        if (Double.doubleToLongBits(this.price) != Double.doubleToLongBits(other.price)) {
            return false;
        }
        if (!Objects.equals(this.prod_desc, other.prod_desc)) {
            return false;
        }
        return true;
    }
    
}

4 November 2019

European Comission recommends against using Microsoft software for privacy reasons

EDPS (the European Data Protection Supervisor) warns member states against using Microsoft software, because privacy of data is not guaranteed. In this EDPS is following an earlier recommendation by the dutch government.

2 September 2019

Spring MVC test example

  • applicationContext.xml snippet
<bean id="loginAction" class="a.LoginAction" scope="request">
  <property name="username" value="#{request.getParameter('username')}"/>
  <property name="password" value="#{request.getParameter('password')}"/>
  <aop:scoped-proxy/>
</bean>
<bean id="userPreferences" class="a.UserPreferences" scope="session">
  <property name="theme" value="#{session.getAttribute('theme')}"/>
  <aop:scoped-proxy/>
</bean>
<bean id="userService" class="a.UserService">
  <property name="loginAction" ref="loginAction"/>
  <property name="userPreferences" ref="userPreferences"/>
</bean>
  • JUnit test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:/applicationContext.xml")
public class ScopedBeanTests {

  @Autowired
  private UserService userService;
  @Autowired
  private MockHttpServletRequest httpServletRequest;
  @Autowired
  private MockHttpSession httpSession;

  @Test
  public void testScopedBeans() {
    httpServletRequest.setParameter("username", "jdoe");
    httpServletRequest.setParameter("password", "secret");
    httpSession.setAttribute("theme", "blue");
    Assert.assertEquals("jdoe",userService.getLoginAction().getUsername());
    Assert.assertEquals("secret", userService.getLoginAction().getPassword());
    Assert.assertEquals("blue", httpSession.getAttribute("theme"));
  }
}

26 August 2019

Detestable (adjective): software that isn't testable.

22 August 2019

Intellij 2019.2 highlights

  • Java Flight Recorder profiling integrated
  • Debugger step into on a line with several methods allows you to select the method to step into
  • Shell script support
  • Code completion also takes into account typos
More...

JetBrains web-types

JetBrains has released the web-types spec to include meta-data for IDE's in web component libraries. They can be used by IDE's for code assistance (completion and the like).
Currently JetBrains did an implementation for Vue.js comonents, whis is supported in JetBrains WebStorm.
The goal is allowing library authors to include such support so they don't have to wait for the IDE builder. Of course it also offloads some work from the IDE builder :)

15 August 2019

Cannon pixma MG5700 scanning problem after windows 10 august 2019 update, error error 2,157,50 [solved]

Today my Canon printer/scanner scanning started to hang when scanning from my windows 10 system over wifi.
The error I got from the IJ Scan tool was 2,157,50 mainly related to network connectivity problems, event though my wifi network was OK.
Scanning documents did not work, scanning mages worked sometimes, but was very slow.
After trying out different things, reinstalling drivers and software for my  printer solved the problem

14 August 2019

Heisenbug [noun]

A software bug that disappears or alters its behavior when one attempts to probe, study, or isolate it.

11 August 2019

JDK distributions

Since Java 11 Oracle has changed the licensing of its Java SE distribution: it is no longer free for commercial use. Oracle's OpenJDK is still free for commercial use. It has the same functionality (although some tools may be missing) but does not get updates once the next version is out (after 6 months). The community, led by RedHat is however updating LTS (Long Term Support) java distributions (8, 11...). A good distribution is AdoptOpenJDK. Several other companies are offering distributions and paid support. You can find a good summary of this on the JetBrains blog.

If you want to download a prebuilt javadoc for local use, you currently have to download it from the oracle Java SE distribution.

AdoptOpenJDK gives you a choice between Oracle's HotSpot VM and OpenJ9 VM, an Eclipse incubator project, based on VM code donated by IBM.

Differences between AdoptOpenJDK en Oracle OpenJDK are  summarized in the table below:

Oracle JDK 8 proprietary component Alternative component OpenJDK 8 OpenJDK 11
Java Web Start IcedTea-Web yes no
JavaFX OpenJFX no no (coming soon)
T2K font rendering engine Freetype yes yes
Monotype Lucida fonts Relicensed Lucida fonts no (coming soon) no (coming soon)
Ductus 2D renderer Pisces/Marlin yes (Pisces) yes (Marlin)
Kodac Color Matching System (KCMS) library LCMS yes yes
SNMP Use JMX (or SNMP4J) yes (not bundled) yes (not bundled)
Sound drivers Use Windows sound drivers yes (not bundled) yes (not bundled)
Java Flight Recorder (JFR) Java Flight Recorder no (coming soon) yes
Java Mission Control (JMC) Use JDK Mission Control no (coming soon) no (coming soon)

Questions about whether design is necessary or affordable are quite beside the point: design is inevitable. The alternative to good design is bad design, not no design at all.

Book design: A practical introduction - Douglas Martin
Good design is imperfect design.
Eric Evans

Beware: removing Google Drive shortcuts

The other day I was happy to have found a (quirky) way to make shortcuts to folders in Google Drive.
Last week I removed the shortcut, as I did not need it anymore...

Today I received a mail of a person with whom I shared a file that it had gone to my recycle bin!
Actually: removing the shortcut had removed the original folder as well!
Good thing I was notified in time and Google had not yet purged it from the recycle bin, which normally happens after a month...

This begs the question: how do you remove a shortcut in Google Drive properly (without removing the original?)

  1. Select the folder (don't go into it)
  2. Open the details tab on the right
  3. Under Location: you will see that their are two parent folders listed. Each one has an x icon next to it.
  4. Click on the x of the parent you want to remove the shortcut from
More...

5 August 2019

identifier cases (updated)

  • ALL_CAPS or TRUMP_CASE
  • CamelCase
    • PascalCase or UpperCamelCase
    • dromedaryCase or lowerCamelCase
  • kebab-case
  • snake_case

4 August 2019

Mapping Maven phases to Gradle Lifecycle tasks

A table summary derived from the Gradle documentation.
Maven phase
Gradle task
Gradle Plugin
clean
clean
Base
compile
classes
Java
test
test
Java
package
assemble
Base
verify
check
Base
install
- (Not needed)
publishToMavenLocal
-
Maven Publish
deploy
publish
Maven Publish

Core language plugins, like the Java Plugin, apply the Base Plugin and hence have the same base set of lifecycle tasks.

31 July 2019

Dutch government recommends against using Microsoft products that do not comply with GDPR

A report by Privacy Company, commissioned by the Dutch government, has found privacy risks in Office 365, Windows 10 Enterprise and mobile apps, that are possible violations of GDPR.
The Dutch government discourages the use of this software.
In a reaction on previous remarks, Microsoft made modifications to Office 365 Pro Plus, which is now in line with GDPR.

more...

24 May 2019

I name all my projects after myself. First Linux, now git.

Linus Torvalds

Any organization that designs a system will inevitably produce a design
whose structure is a copy of the organization's communication structure.

 Melvin Conway

19 May 2019

UMLet: tips & tricks

 My modified palettes

  • I made some diagrams more consistent with UML 2 and modified some elements to make them resize automatically
  • unpack into the palettes folder of Umlet (you may want to make a backup first)

 Dragging elements without sticky relations

When you drag one or more selected elements,  any relation that is close to their borders will stick and move along. Sometimes you do not want that. Just hod down the SHIFT key while dragging to avoid this

 More tips in the FAQ...

UML links (updated)

4 April 2019

OneNote: Looks like this section is corrupted... (fixed)

...OneNote might be able to fix it, but you should avoid working here in the meantime. 

This was the scary error message I received from MS OneNote on my windows 10 system.
This section  lives on Google Drive File Stream, not sure if this has any impact.
These are the steps I tried to solve the problem:

  • OneNote proposes to resync the section. 
    • This does not solve the issue 
  • Online resources suggest copying the pages to another section, the deleting the corrupted section.
    • I did that, leaving some old pages in there.
  • I deleted the corrupted section
    • The section disappeared, but quickly reappeared, still corrupted
  • I removed all pages, I emptied the notebook recycle bin
  • I deleted the corrupted section again
    •  The section disappeared, but quickly reappeared, still corrupted, so I do not think sep 4 had any effect
  • I moved the now empty section to another notebook
  • I deleted the copied section in the other notebook
  • All my notebooks are fine now

22 March 2019

Java 12 is out

Another semesterial java release, feeling more like a Java 9 maintenance update.
Most changes relate to JVM internals, not to the language itself. This reflects how the JVM importance has grown with respect to the language.

Oracle is still mostly tuning its release process. The most notable novelty is indeed in this area: in Java 12 we have the first preview feature: switch expressions. You have to activate it explicitly and then you can work with the feature. Seems like a good way to get real world feedback before casting a feature in stone.

9 February 2019

Java Web Services resources (updated)

22 January 2019

Dozer DTO assembler (upate)

Dozer is a nice little object mapper. It moves data from one object to another.

Dozer can be used as a generic Data Transfer Object assembler. You specify your mappings in an XML file. By default it copies data to properties with the same names, unless you add specific field mappings.

 <mapping>
   <class-a>z.Original</class-a>
   <class-b>a.Kloon</class-b>
      <field>
         <a>identity</a>
         <b>uid</b>
      </field>
 </mapping>

Next you call dozer in your code to move your data:
public Kloon getDto (Original o) {
  return dozerMapper.map(o, Kloon.class);
}
Dozer can reverse map from class-b to class-a as well. There is an annotation based mapping mechanism which works well for simple cases.

MapStruct is a good annotation driven alternative.

17 January 2019

Never trust a feature with the word management in its name.

Venkat Subramaniam

14 January 2019

Windows: Adding tiles to a folder in the start menu (problem)

In the windows start menu you can group multiple tiles under one tile. Just drag one tile over another one and they are both grouped under a folder tile:

Only... it doesn't work with small tiles. Most of the time windows swaps the tiles rather than adding the tile you're dragging in the folder.
Stupid solution for a stupid bug:
  1. Resize the tile you are dragging to to medium size. 
  2. Drag the tile you want to add into it
  3. Resize the folder tile to small again.

13 January 2019

Personally I'm always ready to learn, 
although I do not always like being taught. 

Winston Churchill

6 January 2019

Making shortcuts (links) in google drive

Using the SHIFT-Z shortcut on a file or folder, you can add it to another folder as a link
To remove the link from a location, go to the details of the file/folder. You will see that it has multiple locations. You can remove one of the locations here.
More...