longish introduction
Since the publication of the final specifications EJB3 lot of time has elapsed, and there are more and more implementation of this technology - more or less complete. This probably means that EJB3 will be increasingly popular as the technology base for new projects. So I thought that it's time to explore this technology a little closer. I would like to begin by defining the specifications of the lowest layer of the average webaplikacji - a model of persistent data and interface with a database (or perhaps with JDBC), a Java Persistence API - JPA. In fact, JPA is nothing revolutionary. SFE rather on concepts proven in the most popular ORM framework unless - Hibernate. I enjoy it more that the last two years with Hibernate I had a lot to do. What is more out of Hibernate is an implementation of JPA - and I'm going to use it. Undoubted advantage of JPA is that in a compact and relatively easy way to standardize the basic mechanisms of ORM. JPA interface is not too extensive and advanced applications may prove to be insufficient. The JPA will not find many of the advanced elements of existing frameworks ORM. It has no API to dynamically create search criteria, or it is not possible to define the class as a field enumerated SQL formula. Therefore, JPA implementations available to provide extensions to the basic specification. However, this means that a transparency of the implementation of the JPA specification may be only illusory. From a user perspective Hibernate knowledge JPA is inevitable, and so if you want to use the mapping annotations. However, in the style of the application configurations and EntityManager'a JPA is not necessary - at least for now. Another advantage of JPA is that you can use not only in the EJB3 container, but also in the normal JSE. But no longer have enough of these digressions, so move on to describe a specific example using JPA.matter problem
to do is a model in which the center is being Message - Message, which contains in itself: the subject - title, content - content, and links to the entity User - User in the role of sender and recipient.JPA Configuration
JPA specification specifies that the configuration file should be in your META-INF/persistence.xml. Listing the configuration file of my sample application:\u0026lt;persistence version = "1.0" xmlns = "http://java.sun.com/xml/ns/persistence" xmlns: xsi = "http://www.w3.org/ 2001/XMLSchema-instance "xsi: schemaLocation =" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd "> \u0026lt; persistence-unit name = "jpapg1"> \u0026lt;! - Identify suppliers that implements JPA. -> \u0026lt;Provider> Org.hibernate.ejb.HibernatePersistence \u0026lt;/ provider> \u0026lt;! - \u0026lt;class> \u0026lt;/ Class> You can specify a list of classes of mapping model database. The EJB3 container is completely unnecessary, because the JPA specification imposes the obligation to implement an automatic search classes. This feature however, is not defined when you run in the normal environment JSE. However, Hibernate can be parameterized in order to search for these classes also in the JSE. -> \u0026lt;properties> \u0026lt;! - Bed configuration parameters JPA - Hibernate -> \u0026lt;property name = "hibernate.archive.autodetection" value = "class" /> \u0026lt;property name="hibernate.show_sql" value="true" /> \u0026lt;property name="hibernate.format_sql" value="true" /> \u0026lt;! - Parameters access to the database. -> \u0026lt;property Name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" /> \u0026lt;property name = "hibernate.connection.url" value = "jdbc: HSQLDB file: jpapg1db "/> \u0026lt;property name="hibernate.connection.username" value="sa" /> \u0026lt;property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> \u0026lt;! - Parameter specifying the database schema generation from mapingów. -> \u0026lt;property Name="hibernate.hbm2ddl.auto" value="create" /> \u0026lt;/ properties> \u0026lt;/ persistence-unit> \u0026lt;/ persistence>
data model and mapping
confine myself Listing only on presentation of an example source code, which - at least I hope so - it is enough okroszony comments.User - User
pl.dwalczak.jpapg1.model package, import java.util.List; javax.persistence.Column import, import javax.persistence.Entity; javax.persistence.GeneratedValue import, import javax.persistence.GenerationType; javax.persistence.Id import, import javax.persistence.JoinColumn imports, javax.persistence.NamedQueries; javax.persistence.NamedQuery import, import Javax . persistence.OneToMany; javax.persistence.SequenceGenerator import, import javax.persistence.Table; @ NamedQueries (value = {@ NamedQuery (name = "user.findAll", query = "select u from User u order by asc u.nickName "), @ NamedQuery (name =" user.findByNickName ", query =" select u from User u WHERE u.nickName =: nickname ")}) / / Define a sequence of" users_seq "for the generation primary key table "users". @ SequenceGenerator (name = "users_seq") / / mapping table "users". @ Entity @ Table (name = "users") public class User {private Long id; private String nickname; private letterreceivedMessages; private letter sendMessages / / availability of default constructor is required by the JPA. public User () {} public User (String nickname) {this.nickName = nickname;} / / Primary key table (column "usr_id"), / / \u200b\u200bwhose value is determined by the sequence "users_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "users_seq) @ Column (name = "usr_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id;} / / mapping column usr_nickname "which must have a unique value / / and have a maximum length of 24 characters. @ Column (name = "usr_nickname", unique = true, Nullable = false, length = 24) public String getNickName () {return nickname;} public void setNickName (String name) {this.nickName = name;} / / mapping connections to the table "messages" in the role of the recipient. / / Definition of columns in the table "messages" which is the concatenation (Msg_to "). / / Select the record for being the "User" has nothing to do with the "Message" / / associated by the association. @ OneToMany @ JoinColumn (name = "msg_to", insertable = false, updatable = false) public List getReceivedMessages () {return receivedMessages;} public void setReceivedMessages (Letter receivedMessages) {this.receivedMessages = receivedMessages;} / / Definition connection to the table "messages" in the role of the sender. @ OneToMany @ JoinColumn (name = "msg_from", insertable = false, updatable = false) public List getSendMessages () {return sendMessages;} public void setSendMessages(List sendMessages) {
this.sendMessages = sendMessages;
}
}
Wiadomość - Message
package pl.dwalczak.jpapg1.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@NamedQueries(value={
@NamedQuery(
name="message.findReceived",
query="select m from Message WHERE m.to m =: user "), @ NamedQuery (name =" message.findSend ", query =" select m from Message m WHERE m.from =: user ")}) / / Define a sequence of" messages_seq "for the generate the primary key table "messages". @ SequenceGenerator (name = "messages_seq") / / mapping table "messages". @ Entity @ Table (name = "messages") public class Message {private Long id; private String title; private String content; User from private, private to User / / availability of default constructor is required by the JPA public Message () {} public Message (String title, String content, User from, the User) {this.title = title; this.content = content; this.from = from; this.to = this;} / / Primary key table (column 'msg_id'), / / \u200b\u200bwhose value is determined by the sequence "messages_seq. @ Id @ GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "messages_seq") @ Column (name = "msg_id") public Long getId () {return id;} protected void setId (Long id) {this.id = id; } / / mapping column msg_title "whose value can be up to 64 characters. @ Column (name = "msg_title", length = 64) public String getTitle () {Return title;} public void setTitle (String title) {this.title = title;} / / mapping column msg_content "whose value can be up to 1024 characters. @ Column (name = "msg_content", length = 1024) public String getContent () {return content;} public void setContent (String content) {this.content = content;} / / Mapping to the table "users" - the message sender. / / This link is mandatory - it must be set - and is implemented by the / / foreign key to table "users", which stores the value of column "msg_from. / / This is equivalent to the relationship defined on User.sendMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_from" Nullable = false) public User getFrom () {return from;} public void setFrom (User from) {this.from = from;} / / Mapping to the table "users" - the message recipient. / / This is equivalent to the relationship defined in the User.receivedMessages. @ ManyToOne (optional = false) @ JoinColumn (name = "msg_to" Nullable = false) public User ghetto () {return this;} public void Setto (User to) {this.to = this;}}
Entity Manager
Entity Manager is that in the JPA, which is in the Hibernate Session. The JSE You can obtain it as follows:javax.persistence.Persistence.createEntityManagerFactory ($ PERSISTANCE_UNIT_NAME). createEntityManager ();In EJB3, you can do this by injecting (the container) to the field in the beanie EJB:
javax.ejb.Stateless import; import javax.persistence.PersistenceContext; @ Stateless public class Example implements ExampleBean {@ PersistenceContext EntityManager em; ...} Entity Manager is the starting point to perform such operations as: - the consolidation of the object (the method persist) - queries execution (method and find methods of family group createQuery) - manulnego determining transaction - beginning, acceptance and withdrawal (method getTransaction ())
Query Language query language in the JPA is a JPA-QL (EJB-QL extension) and is very similar to Hibernate'owego HQL'a. I think I used the example queries are simple enough that it does not require comment. Resources
example source files
Java Persistence with Hibernate - Sample Chapter 2
JPA - javadoc
Hibernate Annotations
Hibernate EntityManager
0 comments:
Post a Comment