Monday, February 18, 2013

Java EE: Persists entity beans with generated primary key (SQL Server)

In developing an enterprise application in Java EE, sometimes you would come across a database table with auto-generated primary key. If you're using NetBeans to generante entity beans from a database, you would get something like this:

@Entity
@Table(name = "your_table_name")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "YourTableName.findByTheId", ... )})
public class YourTableName implements Serializable {
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "the_id")
    private Integer theId;


    ...
}

But if you try to persists an instance of the entity bean, you would get an error and you would not be able to alter your database. This is because when you try to persist the instance you would do this

YourTableName yourTableName = new YourTableName();
yourTableName.setFooBarField("foobar"); //example field in table

em.persists(yourTableName);

You could not set the yourself, since it's suppose to be autogenerated by the database. So, in order to solve this, you have to edit the generated entity beans, by adding GeneratedValue annotation to the primary key variable, and also remove the NotNull annotation, like so:

@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "the_id")
private Integer theId;

You have to remove @NotNull since, during persisting, you does not set the value for the primary key. Not removing this would throw an error (at least in my case).

Hope this would help. :) 

Tuesday, February 5, 2013

Java: Base64 Encode

I used this function to encode a string using base64 encoding for my java card applet.

public static String base64Encode(String s) {
    String table="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            + "abcdefghijklmnopqrstuvwxyz0123456789+/";
    String b="";
    String r="";
    int pad;
       
    for (int c : s.toCharArray()) {
        b+=rjust(Integer.toBinaryString(c), 8, "0");
    }
           
    for (int i=0; i<b.length(); i+=6) {
        r+=table.charAt(Integer.parseInt(ljust(b.substring(i, i+6), 6, "0"), 2));
        pad=6-b.substring(i, i+6).length();
        switch (pad) {
            case 0: r+=""; break;
            case 4: r+="=="; break;
            case 2: r+="="; break; }                  
    }
    return r;

}

Both rjust and ljust that you can find in the function above are custom functions similar to python's rjust and ljust.