Rising Functional Programming
The expected shift of computer processing to even greater degree of parallelism has sparked interested in new ways of developing software that will take full advantage of the horizontal increase in processing power. The key area that has received the bulk of attention is programming languages and tools. In a many-core world (as opposed to what is now called multi-core), shared state becomes very tricky so most of the mainstream programming languages would be difficult to use in producing software. While almost all the mainstream imperative languages do have a library to enable the development of code capable of parallelism, most of these methods are not baked into the language and sometimes the initial design of the language itself gets in the way. In the design of most of the mainstream imperative programming languages, immutable data type are rare or sometimes completely non-existent all together.
Increased interest in functional programming languages have given rise to new languages that serve as an adequate bridge between the existing imperative programming mindset and the much needed shift to a world of parallelism. Functional programming is certainly not new as many of the techniques have been implemented in languages like Scheme, Haskel, Erlang amongst others. However, these languages and the ideas that they implement have largely remained in academic circles until recently when the software industry has taken a more proactive role to transfer the knowledge of academia to the industry. Programming languages like F# and Scala borrow heavily from the aforementioned pioneers of functional programming.
The newest in this growing list of new programming languages is Google’s Noop. The following is a description of Noop from the project’s web site:
… new language experiment that attempts to blend the best lessons of languages old and new, while syntactically encouraging what we believe to be good coding practices and discouraging the worst offenses. Noop is initially targeted to run on the Java Virtual Machine.
The basic assumptions in the design and development of Noop are certainly interesting. Integrating testing into the programming language can greatly improve code quality and making the language truly object oriented will improve its readability. I have found functional programming languages to have a pleasantly concise syntax that effortlessly achieves what would have required a ton of boilerplate code in supposedly OO languages like Java or C# which include primitive data types.
Programming Paradigms
In the past I enjoyed the concept and practice of programming because it provided an opportunity to explore a way of thinking about a problem without the usual constraints that one may face in the real world. The greater challenge (hence satisfaction) is in defining a model that will account for any potential failures and still be able to accomplish its intended purpose. As time passed, I have come to focused specifically on design and the resulting architecture. Designing anything is a process of creating a model that can account for the solutions to aspects of the problem specified. That is reductive in and of itself but there are much more insightful aspects of problem solving that need to be taken into account in designing and developing a solution.
In any design effort, the ability to abstract from the problem remains imperative while the generally accepted adage of too much of [take-your-pick] is a poison applies, abstraction done right can provide a practical solution to a multitude of problems. Programming paradigms have always been about creating models that either provide a way for us to give instructions to computers or a way for us to describe the world in a manner that a computer can comprehend and hence process. Programming languages remain a way for humans (programmers, software engineers, etc) to interact with a computer – giving it instructions on what to do and how to handle the particulars of our reality. The models that are implicitly encoded into programming languages represent our thinking as far as the machine-like view of the world or bringing the machine closer to the way we appreciate the world.
What are generally referred to as low level programming languages were essentially intended to enable us to communicate with computers and as such they bare close relationship to the way in which computers operate. Think of the assembly language and how you program in it.
With time, additional abstractions were added that allows us to focus more on giving computers instructions as opposed to prescribing the manner in which the computer carries out our instructions. This focus on instructions gave raise to what are generally referred to as procedural programming languages in which the emphasis was on results of the operations that need to be accomplished. The ability to focus on what you want done and how it is achieved in steps, obviously led to a greater interest in using computers to carry out what are essentially repetitive tasks that could easily be encoded in a number of functions which can then be executed and produce the desired result (or report errors, if any).
This focus on the procedures that are needed to accomplish a task leads to a huge codebase that is both hard to maintain and/or evolve to meet new and/or changing circumstances. This great problem would apparently seem to come from the fact that the procedural way of software development, does not adequately account for how the real world operates. In the real world, things exist and operate as a single unit – there is no difference between what something is and what it does.
Personally, I get the impression that this is the time when programming became a bit more philosophical in a sense that there is a deliberate effort to model the world in terms of its nature and its essence. The nature of the world, describes what the world is: in OOP, this is simply described as the state of the an object which is typically denoted by properties/attributes/fields, depending on the terminology of your platform of choice. You may notice that the nature of objects so defined does not need to change in order to make things happen because OOP relies on message passing to get Objects with the appropriate nature to carry out the intention of their essence as defined by their nature (what you do is defined by your nature and your nature defines what you do).
While OOP allows for a better abstraction from the real world, the manner in which it has been implemented thus far has a serious short coming. All the OOP languages that I have come across are rather verbose as the design process need to describe any application elements of the problem space in code. With increasingly large programs, it comes much more challenging to maintain large programs or ensure that they are tested to the satisfaction of end users. So, testing frameworks have mushroomed around OOP languages such as Java with JUnit (among so many others).
For all intends and purposes, OOP still bears some lingering association with how a machine would go about processing instructions. The so-called Fourth Generation Languages (4GL) like the Structured Query Language (SQL) has shown us to go about expressing our intention to the machine and have the machine figure out the means of getting to our intentions or at the very least least as close to it as possible. The oft-referenced Moore’s law continues its march into ever more powerful machines albeit in a slightly different way. With powerful processors, driving our computers we do not have to be chained to the vagaries of machine type thinking.
Another more poignant point to consider is the increased use of computers for entertainment (gaming etc), business and socializing. The nature of the problems that face social networking applications are markedly different from what have faced businesses at the advent and development of the current mainstream programming language. A business environment invariably has some kind of structure around it which is encoded in policies, procedures, organization structure and the processes that the organization run. Starting from such a foundation, it is then possible to formulate a few procedures which can be executed at regular or ad hoc basis to great effect. However, consider the way in which social networking sites are used – a single person would have a Facebook account, a Twitter account, YouTube account in addition to web mail accounts. These applications have become people centric and the number of people involved an quickly become a challenge for social networking sites that have managed to garner a big enough following.
The social network craze reveals an interesting dimension of how programming languages have evolved over time. At the outside, a few academicians used computers to help with research and then the business world caught on and now we have to face the reality that perhaps programming languages need to be less rigid. Often when discussing IT related subjects, less rigid may easily lead to less secure though in this context less rigid but more robust would be the best outcome in the evolution of programming languages. Objects are good as way to model the world but they lack a certain degree of expressiveness in effectively illustrating and modeling the state of the world as a seen a person who cares more about getting things done and less about the steps taken to get to the end.
Would you Upgrade to a less Secure Windows 7?
The beta of the next release of Windows has been making rounds and has garnered mostly positive reviews as a beta with most people having good things to say about performance. Windows 7 essentially addresses the short comings of Windows Vista and top on the list of Vista’s transgressions is the User Account Control (UAC) feature which was intended to make Windows more secure but it proved to be too zealous in its prompts for permissions. Changes in Windows 7 aim to reduce the number of prompts that UAC asks for but so far this may have led to a less secure configuration on the next release of Windows.
According to two Windows enthusiasts, the current configuration of UAC on the beta version of Windows 7 makes the next release of Windows vulnerable. One of these threats allows malware to turn off UAC. A nasty piece of code would take advantage of your Windows 7 box without any protest from your system. The second flaw allows malware to elevate its permission on the system. The details of the second exploit can be found here. It basically take advantage of the fact that processes that ship with Windows 7 are allowed to automatically elevate their permissions on the system without any UAC prompt. However it is possible to use a binary that ships with Windows 7 to launch a third party program which can be a malware thus allowing malware free pass into your system.
The incredible and perhaps scary bit of this drama is Microsoft’s response to these flaws: so far, the response from Microsoft is that these two issues are not flaws but are there by design. In what world does make it sense to insist that an apparent security vulnerability is there by design, unless the intention was to have a vulnerable design from the outset. I don’t buy that “by design” argument as it seem to be based on the fact that there is absolutely no way that malware can find its way into a Windows 7 system in the first place thus making it all right to make flawed design choices.
The reaction to and interest in Windows 7 has been phenomenal to say the least and personally I was impressed by the fact that Microsoft is getting the benefit of what comes as part of the open source software development: community support and involvement in software development. These two security issues were raised by Windows enthusiasts and raised using a beta release for that matter; the upside is that this gives Microsoft the chance to fix the vulnerability before releasing Windows 7. More importantly fixing the vulnerability would be important in cementing relationship between Windows hackers from the broader end user community and Microsoft such that cooperating towards securing Windows becomes an imperative of everyone in the Windows ecosystem.
UAC in Windows Vista was annoying but I have always thought I much rather get used to the annoyance of UAC than to suffer malware infestation which would dramatically increase the amount of time I spend baby sitting Windows. The UAC changes in Windows 7 are implemented to lessen the annoyance that was in Vista but there exists a real threat of these changes causing Windows 7 to become less secure. It is a delicate balance between security and usability and missing that balance can shape end user’s reaction to a product. How Microsoft deals with this so called by design flaw can possibly shape people’s attitude towards Windows 7. To Microsoft the more important question is how many people are willing to hang on to Windows XP because of the perceived vulnerabilities in Windows 7.
Impressions of Windows Internet Explore 8 Beta 1
The browser is king in an increasingly web-centric world and I don’t mean web-centric in the manner of communication – email, chat etc (which are certainly important) but increasingly people are relying on web application to carry out LOB (Line of Business) tasks and activities. With that in mind, the browser has taken a central role in computing generally. Microsoft owns the browser market and has done so since it successfully trounced Netscape in the now infamous browser wars. However, the sweet taste of victory and perhaps also some arrogance and complacency about its market, Microsoft decided that the browser was no longer worth its attention (Just look at IE 6). As you may be aware Firefox changed Microsoft’s view of the browser and spurred them to put more resources into the development of IE which brought tabbed browsing to IE with the release of IE 7. Microsoft’s work is not done as yet since IE has never really supported standards other than what Microsoft thought was best. Don’t get me wrong, initiatives by individual players in a particular software category could lead to increased innovation in the category but alas that is a post for another time.
The follow up to IE 7 has just been released in the name of Windows Internet Explorer 8 Beta 1. This beta release is targeted at web developers and designers and includes ’super standards’ mode that the browser uses by default. Not that there are super standards but the simple meaning of the super standards mode is that IE 8 will adhere to web standards more closely when displaying web content. The inclusion of super standards mode as the default rendering engine means some additional work for developers and designers who want their wares to use anything but the super standards mode. The additional meta-tag added to web pages to trigger non-super-standards mode rendering on IE 8 is a testament to the continue special treatment that will be lavished upon IE when developing and designing web sites. It is not all lost though since I believe that making super standards mode the default for rendering will in the long run result in web designers and developers producing more standards compliant web sites.
I just installed IE 8 Beta 1 and I am kind of impressed by the installation experience. The download size was not that big but then again this is still an early beta – who knows what will happen by the time IE 8 is ready for release. The installation went on without any glitch. I should mention that I decided to install the beta because of IE 7 emulation which ensures that I get IE 7 rendering when I need it (though it requires a browser restart at the time of this writing).
I chose not to accept the default settings for my personalization of IE 8 Beta 1 which meant that I got all the options that are there with regard to search engines, web providers etc (I was not aiming to produce a professional account of my installation experience
). Of course IE 8 offered to make itself the default browser on my machine but that honor currently belongs to Firefox (though for some reason, I can’t get Google Desktop Search to use Firefox for display even though it is the default browser but I digress). IE 8 customization offered to import my settings from my “other” browser which in this case is Firefox. The interesting part of the customization was when IE 8 detected the Firefox extensions I have installed and offered to find similar extensions.
The search for IE extensions took me to Windows Market places (windowsmarketplace.com) which looks rather wrong with IE 8 super standards mode running. Notice how the web site’s navigation bar is out of place?
Microsoft Volta: Multi-tier applications simplified
Today, I woke up to an interesting headline: Microsoft’s Volta project has been released through Microsoft Live Labs. I am not exactly sure of the details of how Volta works but early impressions are that it is fundamentally Microsoft’s response to GWT (Google Web Toolkit); never mind the fact that Microsoft seems to be doing quite a bit of this responding business. So briefly, with Volta you design your applications as you would any desktop application (single tier) and when your code & design wizardry is done you then invoke Volta to turn your application into a web application which is usually multi-tier with each tier running on a different machine or at the very least a different process.
The Context
Developing web application involves the comprehension and appreciation of a number of technologies since web application span multiple runtimes, each with its own idiosyncrasies which typically make sense in each context. A web application stores data in a database which is more likely to be a relational database and as such SQL is the default language used in the database layer. On the presentation layer, the web application interacts with the end user through a browser which typically understands JavaScript, CSS, HTML and so many others through plugins. The browser also makes use of XML and JSON (JavaScript Object Notation) for its data. Finally, in between the database and the browser sees the application tier that binds the other two tiers together; as you may already be guess, this lay runs on the web server and includes Java, PHP, Python, C#, VB.NET, Ruby etc.
Microsoft’s .NET framework is increasing showing up just about everywhere though it is still fundamentally attached to the Windows OS. There is SQLCLR which is embedded into Microsoft SQL Server (from version SQL Server 2005 going forward). On the middle tier (application layer) there is the normal CLR and Silverlight covers the presentation layer. Recent extensions to the .NET programming languages in form of LINQ for C# 3.0 and VB.NET 9.0 introduced a standardized query syntax to enable uniform expression of queries across disparate data sources. Through the use of annotations, LINQ – SQL and LINQ – Entities enables CLR supported rewrite of code from the LINQ compliant programming languages to the appropriate data model in each context.
How it is
Volta works on Microsoft Intermediate Language (MSIL) code and as such it assumes ubiquity of the .NET framework, at least during the development stage; MSIL is the same stuff that .NET compliant programming languages compile to. As you may be aware, Microsoft’s CLR includes a wealth of meta data that can be used for various purposes by tools that understand the meta data. So Volta makes use of the meta data that is compiled into the MSIL code to make a multi-tier application out of a single tier application. Volta leverages the rich meta data to achieve refactoring, retargetting and remodulating.
Refactoring is central to turning single tier code to multi-tier, distributed code as illustrated in the diagram below. The split of the architecture is directed through use annotations on the original single-tier code. So essentially Volta rewrites your application using directions that you provide through annotations effectively providing a translation of your .NET compliant code to JavaScript. From the Volta website:
The Volta rewriter automatically creates and deploys the marshalling and security code necessary to execute the code on multiple tiers. The following diagram illustrates evolution of a Volta application from single-tier architecture to a distributed, multi-tiered architecture.
Source: http://labs.live.com/volta/docs/
Volta achieves its objectives through automation and this also presents a huge opportunity to dynamically target the code that Volta produces to the appropriate platform and runtime hence optimizing it as much as possible. This enables Volta to target platforms but also increases the number of possible tiers that an application can be split into.
From the Volta site once again:
Volta hides as many browser-specific differences as possible, but still allows developers to leverage the unique capabilities of particular browsers. Instead of targeting solely the intersection of browser capabilities, Volta targets the entire union, but makes the intersection browser-agnostic. This is browser remodulating. From the developer’s point of view Volta attenuates browser differences. But what about testing and debugging? Volta and the Visual-Studio integration supports debugging and testing of applications with full transparency. Visual Studio’s Solution Platform dropdown lets us choose the specific browser we want for a testing/debugging session. This allows us to see how each browser renders the HTML.
Resources:
- Democratizing the Cloud by Erik Meijer (MSR)
Simple Java Persistence API (JPA) Demo
One of the most visible obstacles to effective learning, IMHO, are wizards and various sorts of automation tricks used to simplify life for a developer. Now, before you jump off the edge and narrate a list of the benefits that tools in general provide let me just clarify that I am not against tools but newbies should not be introduced to tools when they are learning to develop software. I tend to think that it takes focus away from the details of the development process. So, I have been playing around with Netbeans 6.0 and I am quite impressed by the new features and amazed by how productive they can make developers. As with all tools, you tend to get used to the way Netbeans does things and soon enough you wouldn’t know how to find your way around a compiler argument.
One of the most interesting features in Netbeans 6.0 is its support for JPA (Disclaimer: that is not a scientific stance … feel free to let me know of any better JPA experiences). While Netbeans 6.0 makes developing CRUD applications easy, I felt like I was learning how the Netbeans team view JPA and I would like to have an appreciation for the technology on its own or at least as far low level as I can go at this point.
I set out to implement a small application without the support of Netbeans or any IDE. A text editor with syntax highlight support would suffice for this task. After starting out with a single class, I discovered that my Java development environment was not setup nicely; I guess, I never got around to customizing it after formatting my hard disk. The process of setting up the environment made me realize that I couldn’t possibly do the demo with a text editor and the compiler alone. I needed a tool to help me with the compilation and of course subsequent execution. Besides, such a tool would also allow the demo to be somewhat portable. I decided to setup Apache Ant. I especially didn’t want to have to add all the jar files that I need for this demo to some environment variable and of course doing that would tie the demo to my machine.
Overview of Object Relational Mapping
The most common and popular method of storing data is in relational database though this by no means means that it is the only way of storing data. Most business application need to interact with a relational database at some point in their running and due to data-centric business operations, the data stored in the relational databases will last longer than most of the applications used to handle it. Object oriented software development has caught on and most of the popular programming languages are either purely (to some extend) OO or are capable of supporting OO concepts. OO is great for application logic and relational databases are great for data storage and manipulation but clearly these two are based on two different paradigms. The definition of a class is not so different from a definition of a table but there are concepts in either of these paradigms that doesn’t neatly map into the other. For example there is no equivalent of OO’s inheritance in the relational paradigm but inheritance can be represented. The mismatch between these two paradigms is usually reference to as the Impedance mismatch.
In order to develop applications, software developers have had to overcome the impedance mismatch and earlier efforts had been tedious since it is upon the developer to retrieve the data from the relational database and then transform it into objects which are then handled by the business logic. When it is time to send the business objects to the database, it is once again necessary to transform the object into a format that makes sense to a relational database. This back and forth movement between the OO and relational paradigms can be automated to some degree by defining an bridge between the two such that this bridge is able to transform back and forth with minimal involvement of the developer.
This is the need that ORM products address and most of them prescribe the definition of the mapping between the OO and relational paradigms; earlier ORM technologies made use of XML to specify the mapping between classes and tables. While the EJB standard require objects to implement interfaces and extend classes in order to benefit from ORM. The EJB approach typically targeted large scale enterprise application which left the small-medium scale application uncovered with regard to persistence though yes you can argue that JDBC was adequate for the needs of the small-medium scale application developers. For the Java community TopLink and Hibernate have been popular ORM products in the commercial and open source space respectively. For the Java community, it became necessary to standardize the persistence technologies that are in use and that’s how the JPA (Java Persistence API) comes into play.
The Idea of the Application
The application in this scenario manages the rooms in a hotel. From outset, the emphasis of the application will be more on the model than its capabilities – after all the objective is to get a hands on experience with JPA. This also mean that any UI enhancements will be added later on (… at least eventually?
).
The application will enable the user to keep track of hotels; hotels have rooms and rooms have features and characteristics that distinguish them from all others.
Objectives
- Demonstrate the basic CRUD capabilities of JPA without the use of an IDE
- Portability across database products supported by JPA
- The application should be self contained – doesn’t need a large, network based, multi-user RDBMS to implement
The Design
The application will be designed in 3-tiers though for the moment, I am more interested in the database layer and application layer. So, for the database … we will not worry too much about which database we are using because one of the objectives is to have the demo portable across the vendor divide which of course means that we are not going to leverage features specific to a particular database product (not that we need to do that).
The original database was developed on Apache Derby in order to achieve the objective of having the application self contained. Apache Derby can be configured as a network server but in this application it is configured as an embedded database. There are obvious performance implications as a result of using an embedded database but portability in the design should make it easy to switch to the network server installation of Apache Derby or move up to something much larger like MySQL or perhaps even Microsoft SQL Server. While working on the application, I couldn’t have Apache Derby’s tools connected to the database and run the application successfully at the same time. Multiple access to the database was not allowed.
A bit of a background on the database selection process: the original intention was to use SQLite as the database but the JPA implementation distributed with Sun’s GlassFish Application Server does not support SQLite as a database at the time. Other embedded database products considered included HSQL and PointBase and of course Apache Derby.
For the business layer, I have the following objects identified:
| Object Name | Description |
| Hotel | Network operator client |
| Room | A Hotel room |
| Feature | A feature |
| FeatureGroup | Enables features to be group under one category and thus make it easier to ensure sensible feature assignments to rooms e.g. Single bed and double bed are two separate features but both can be assigned to the same room. Putting these features in one category would make it easy for the application to do validations so as to ensure sensible features are chosen for the rooms. |
The Java Persistence API
From Sun:
The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.
The JPA is developed as part of EJB 3.0 (JSR-220). EJB is a standard server-side component model implemented in application servers to enable them manage transactions, object distribution, concurrency, security, persistence, and resource management. These capabilities are automatically provided to distributed business applications that run in a compliant application. Included in the list of EJB capabilities is persistence and in EJB 3.0 that is the part of the architecture that is handled by JPA.
Entity
This is a Java class that represents an object in the domain model and as such its state can be persisted to a data store for late retrieval. Java Persistence API does its magic on what is commonly referred to as a Plain Old Java Object or simply POJO. A normal Java class is marked as an entity either through annotations or in an XML mapping descriptor.
Entities support inheritance, polymorphic associations, and polymorphic queries. Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.
The state of an entity is represented by instance variables, which may correspond to Java-Beans properties. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods. Instance variables must be private, protected, or package visibility. The mapped state of an entity needs to be accessible to the persistence provider at run time so that the provider can update the database when the state of the entity changes. There are two ways of accessing an entity’s state:
- Field Access: annotating the fields of the entity (as shown below) will cause the persistence provider to by-pass the getter and setter methods of the entity class. Notice that the getter/setter methods may or may not be present but they are ultimately ignored by the persistence provider.
- Property Access: when this method or mode of access is used the getter/setter methods must be present. The annotations are placed on the getter methods of the entity.
The JPA puts some requirements on a Entity class as follows:
- The entity class must have a no-arg constructor. The entity class may have other constructors as well.
The no-arg constructor must be public or protected. - The entity class must be a top-level class. An enum or interface should not be designated as an entity.
- The entity class must not be final. No methods or persistent instance variables of the entity class may be
final. - If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the
entity class must implement the Serializable interface.
The Annotations
JPA leverages annotations to implement object relational mapping but it is by no means the only way to achieve mapping. To understand the need for annotations, just consider the number of frameworks and APIs that make use of XML for configuration. It has become complicated to manage the large number of XML that can be found in one JEE project.
JPA specific annotations are colored orange in the above code sample and their simple and brief explanation follows:
Code Sample
package model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.OneToMany;
import javax.persistence.JoinColumn;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.util.Date;
import java.util.Collection;
@Entity
@Table(name=”tblHotal”)
/**
* Hotel class
*
* @author Imma
*/
public class Hotel
{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id;
@Column private String name;
@Temporal(TemporalType.TIMESTAMP) private Date dateCreated;
@OneToMany(mappedBy=”hotel”) private Collection<Room> rooms;
public Hotel(){}
public void setId(int id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setRooms(Collection<Room> rooms){ this.rooms = rooms; }
public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; }
public int getId() { return this.id; }
public String getName() { return this.name; }
public Collection<Room> getRooms() { return this.rooms; }
public Date getDateCreated() { return this.dateCreated; }
}
@Entity: marks an class as an entity. It is normally used to mark classes but can also be used to annotated subclasses and superclasses which may persist to different tables.
@Table: this annotation provides the mapping details between the entity class and the database table to which data about the entity is to be persisted and subsequently retrieved.
@Id: identifies a field of the class as simple primary key. It can be used in conjunction with the @GeneratedValue annotation for simple primary keys that are automatically generated by the database using an auto increment feature that is common with most RDBMS.
@GeneratedValue: identifies an attribute such as a primary key field that is automatically generated.
@Column: this annotation tag is used to mark the column to which an attribute of an entity is persisted to. By default it takes on the name of the attributes which is being annotated. It can be placed on a field for field access or on a method for property access mode. In the above code sample the entity attribute name is annotated with the @Column annotation tag and since the name of the column is not specified, the JPA runtime assumes that name of the column is the same as the name of the attribute.
@Temporal: used to make a date, time or timestamp field.
@OneToMany: associations between entities can be bidirectional. For example, in the example application: a hotel has many rooms thus many rooms belong to one hotel. In order to fully express this relationship, two mappings are required. The relationship between a hotel and its rooms, with the hotel as the owning entity is marked using the @OneToMany annotation as shown in the code sample above. The inverse of this association is using the @ManyToOne annotation which is described next (after the code sample below).
The Room Class code is shown below; a hotel has many rooms and a room belongs to one and only one hotel. Notice how the relationship/association between the two classes is achieved using annotations and JPA. In addition to this, a room has features and a feature can below to more than one room. Conversely, a room has many features.
package model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.ManyToOne;
import javax.persistence.ManyToMany;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.util.Date;
import java.util.Collection;
@Entity
@Table(name=”tblRoom”)
/**
* Room class
*
* @author Imma
*/
public class Room
{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id;
@Column private String number;
@ManyToOne @JoinColumn(name=”fkHotel”) private Hotel hotel;
@ManyToMany
@JoinTable(name=”tblRoomFeatures”, joinColumns=@JoinColumn(name=”fkRoom”),
inverseJoinColumns=@JoinColumn(name=”fkFeature“))
private Collection<Feature> features;
public Room() {}
public void setId(int id) { this.id = id; }
public void setNumber(String name) { this.number = number; }
public void setHotel(Hotel hotel) { this.hotel = hotel; }
public void setFeatures(Collection<Feature> features) { this.features = features; }
public int getId() { return this.id; }
public String getNumber() { return this.number; }
public Hotel getHotel() { return this.hotel; }
public Collection<Feature> getFeatures() { return this.features; }
public String getFeaturesAsString(){
StringBuilder sb = new StringBuilder();
sb.append(“{“);
for(Feature f : features){
sb.append(f.getName());
sb.append(“, “);
}
if(sb.length() > 2)
sb.delete(sb.lastIndexOf(“,”), sb.length());
sb.append(“}”);
return sb.toString();
}
}
@ManyToOne: this is an annotation that is used to map a many to one relationship between entities. For example, in the code sample above a Room belongs to a hotel and a hotel has many rooms. I think it is easier to think of it as mapping many rooms to one hotel hence Many-To-One. Depending on how you named your columns in your database, you may need to use an additional annotation to complete the many to one mapping.
@JoinColumn: at the simplest level, this annotation is used to indicate columns in a database table that are involved in a relationship. This relationship could be a many to one as described above or a many-to-many relationship, as described below. In a many-to-one relationship, the @JoinColumn annotation is used to indicate the foreign key in the entity’s table.
@ManyToMany: this annotation is used to mark many-to-many associations between entities. In relational databases, this would involve the use of a joining table and the @JoinTable annotation is used to indicated this joining table as part of the @ManyToMany annotation.
@JoinTable: this annotation is basically used to mark a joining table for a many to many association. The joinColumns attribute of this annotation is used to indicate the columns that related the owning entity (Feature in the example below) to the other side of the relationship (Rooms in the example below). The inverse of the relationship is indicated using the inverseJoinColumns attribute of the @JoinTable annotation as indicated in the code sample below.
package model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.ManyToOne;
import javax.persistence.ManyToMany;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.util.Date;
import java.util.Collection;
@Entity
@Table(name=”tblFeature”)
/**
* Feature class
*
* @author Imma
*/
public class Feature
{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id;
@Column private String name;
@Column private String description;
@ManyToOne @JoinColumn(name=”fkFeatureGroup”) private FeatureGroup group;
@ManyToMany
@JoinTable(name=”tblRoomFeatures”, joinColumns=@JoinColumn(name=”fkFeature”),
inverseJoinColumns=@JoinColumn(name=”fkRoom“))
private Collection<Room> rooms;
public Feature() {}
public void setId(int id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setDescription(String description) { this.description = description; }
public void setRooms(Collection<Room> rooms) { this.rooms = rooms; }
public void setGroup(FeatureGroup group) { this.group = group; }
public int getId() { return this.id; }
public String getName() { return this.name; }
public String getDescription() { return this.description; }
public Collection<Room> getRooms() { return this.rooms; }
public FeatureGroup getGroup() { return this.group; }
}
This is part one of this demo. Part II will dwell on how JPA comes to life. If you have any comments and questions, please let me know through the comments section of this blog.
