Java for Web Learning Notes (99): A Study of Persistence (4) JPA Small example (next) __java

Source: Internet
Author: User
Tags commit generator microsoft sql server
Mapping of entity

Although in front, we gave the table. But the book recommended that we first design the code, and then according to the code to design the database, user requirements-"code design-" Database design. But I think big projects might not be like that. mapping of classes and data

Indicates that this is @javax. Persistence.entity, the name of the default Entity is the class name, which, if necessary, can be done by using the name parameter.
@Entity (name = "Publisherentity")/
* Can not be set, the default table name is Entity name, if not set, this example is publisherentity, the table name is publishers. If we allow the creation of tables (note that this is dangerous and should be prohibited in a production environment). We can set other keys outside the primary key, for example:
 * @Table (name = "Books",  //table name
 *        uniqueconstraints = {@UniqueConstraint (name = " Books_isbns ", ColumnNames = {" ISBN "})},//Unique key
 *        indexes = {@Index (name =" Books_titles ", columnlist =" Title ")}//Key */
@Table (name =" Publishers ",
       indexes = {@Index (name =" Publishers_names ", columnlist =" Publi Shername ")) 
//Can not be set, defaults to Accesstype.property, indicating that the column name of the table is based on the getter and setter methods, that is, the Java Bean property Another value is the Accesstype.field, that is, according to the FIELD name. The default value should generally be used.
@Access (Accesstype.field) Public
class Publisher implements serializable{...}
PRIMARY Key mappings: Single primary key
@Entity (name = "Publisherentity") @Table (name = "Publishers", indexes = {@Index (name = "Publishers_names", columnlist = "P")  Ublishername "))}) public class Publisher implements serializable{private long ID;
    This is the field private String name;

    Private String address; /* For tag annotation, we either load field, or both load property, do not mix, avoid confusion * "1" We must first set surrogate key, that is, the primary key in SQL, may be a single row, It may also be a federated primary key. *///1.1 "Set primary key."
    The primary key is unique if the code does not set @id and if there are GetID and SetID, the method is considered @id. @Id//"2" set automatically generated value//2.1 "if the MySQL primary key is auto_increment (known as Identity in Microsoft SQL Server and Sysbase), it is @generatedvalue (stra Tegy = generationtype.identity)///* 2.2 Sets the primary key generation by generator. The generator is globally valid and can be used after one setting, and the builder definition can be on class, but the @generatedvalue must be on the property or field.
    There are two species of generationtype.sequence and generationtype.table, corresponding to @sequencegenerator and @tablegenerator.
    ➤ @SequenceGenerator, how to produce the value of the primary key (called sequence in Oracle, the production of the serial number), the attribute has InitialValue (default 0 of the initial value), Allocationsize (step value, default 50). ➤ @TableGenerator, use a special table to hold the current serial number, as shown in the example: using the table Surrogatekeys, the primary key is TableName, the value is publishers, the other column is keyvalue, the initial value is 11923, and the step is 1; that is, when you add a entry to the current table, Surrogatekeys in the table tablename= Publishers KeyValue plus one and takes this value as the value of the entity ID (listed as PublisherID). Note that the default values for Table,pkcolumnname,pkcolumnvalue,valuecolumnname are not specified in JPA, so different implementations can be different, and in order to avoid ambiguity, it is recommended that you define them explicitly. However, we rarely use this approach and may be used for historical legacy projects. Generationtype.identity or generationtype.sequence can meet our requirements */@GeneratedValue (strategy = generationtype.table,
                    Generator = "Publishergenerator") @TableGenerator (name = "Publishergenerator", table = "Surrogatekeys", Pkcolumnname = "TableName", Pkcolumnvalue = "publishers", Valuecolumnname = "KeyValue", Initialv Alue = 11923, allocationsize = 1)//"3" @Column parameter name for the setting//@Column of the column: Specify column name; insertable and updatable are permissions//@Colu Schema-dependent parameters of mn/*-nullable:null or not NULL; *-unique equivalent to @uniqueconstraint, default to FALSE; *-Length for VA Rbinary and varchar lengths, default to 255; *-scale and precision for decimal; *-columndefinition specifies the SQL for the generated column, but because different SQL Server is in the statement There'll be a district.No, once used, it is difficult to migrate to other databases, so it is not recommended * * @Column (name = "PublisherID") public final long getId () {return id; }
}
PRIMARY Key mappings: Composite primary keys

Mode 1: Using @idclass

The table somejointable has a federated component (Fooparenttablesk,barparenttablesk) with the following code:

public class Jointablecompositeid implements serializable{
    private long fooparenttablesk;
    Private long Barparenttablesk;

    Public long Getfooparenttablesk () {...}
    public void Setfooparenttablesk (long Fooparenttablesk) {...}
    Public long Getbarparenttablesk () {...}
    public void Setbarparenttablesk (long Barparenttablesk) {...}}

@Entity
@Table (name = "Somejointable")
@IdClass (jointablecompositeid.class) Public
class Jointableentity implements serializable{
    private long fooparenttablesk;
    Private long Barparenttablesk;
    ...

    @Id public
    Long Getfooparenttablesk () {...}
    public void Setfooparenttablesk (long Fooparenttablesk) {...}

    @Id public
    Long Getbarparenttablesk () {...}
    public void Setbarparenttablesk (long Barparenttablesk) {...}
    ...
}

Mode 2: Using @embeddedid

We see mode 1 where the getter and setter codes have duplicates that can be used in the following way:

@Embeddable public
class Jointablecompositeid implements serializable{
    private long fooparenttablesk;
    Private long Barparenttablesk;

    Public long Getfooparenttablesk () {...}
    public void Setfooparenttablesk (long Fooparenttablesk) {...}
    Public long Getbarparenttablesk () {...}
    public void Setbarparenttablesk (long Barparenttablesk) {...}}

@Entity
@Table (name = "somejointable") Public
class Jointableentity implements serializable{
    private Jointablecompositeid ID;

    @EmbeddedId public
    Jointablecompositeid getId () {...}
    public void SetId (Jointablecompositeid id) {...}}
Data Type Mappings
data type of the property in JPA data type of column in the database
Short,short SMALLINT, INTEGER, bigint or corresponding type
Int,integer INTEGER, bigint, or corresponding type
Long,long bigint or the corresponding type
float, float, double, double, BigDecimal DECIMAL or the corresponding type
Byte,byte BINARY, SMALLINT, INTEGER, bigint or corresponding type
Char,char CHAR, VARCHAR, BINARY, SMALLINT, INTEGER, bigint or corresponding type
Boolean,boolean BOOLEAN, BIT, SMALLINT, INTEGER, BIGINT, CHAR, varchar or corresponding type
Byte[],byte[] BINARY, varbinary or corresponding type
Char[], character[],string CHAR, VARCHAR, binary,varbinary, or corresponding type
Java.util.Date, Calendar DATE, DATETIME, time, or corresponding type, need to be added @temporal
Java.sql.Timestamp Datetime
Java.sql.Date DATE
Java.sql.Time Time
Enum SMALLINT, INTEGER, BIGINT, CHAR, varchar, or the corresponding type, can be changed by @enumerated to the storage mode, described later.
Serializable varbinary or corresponding type, for Java serialization and deserialization

/* Use @basic to match the type in the previous table, optional indicates whether it can be null, and this example indicates not NULL. For prototypes, such as int,double, there is no null for this, so when the prototype does not set option description, the database must be NOT NULL
/@Basic (optional=false) public
final String GETISBN () {return
   ISBN;
}

Set Persistence The persistent unit scope is the configuration and entity class, where the Entitymanager instance can only be oriented to the continuation element and cannot be crossed. The entity class can belong to multiple units of persistence. The continuation unit is configured through Persistence.xml and must be placed under meta-inf/. A Web project has multiple Meta-inf:

Mappings.war!/meta-inf  This is not in the classes/directory, cannot be accessed by class files, used to place the files required by the servlet container, so it cannot be placed here
mappings.war!/web-inf/ Classes/meta-inf is  placed here, in Eclipse, that is, to connect meta-inf/mappings.war!/web-inf/lib/something.jar!/under resources/
Meta-inf  This is the Meta-inf directory with the other jar packs, and we're not going to put it in, and it only works in the jar package


Here is an example of persistence.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <persistence xmlns= "Http://xmlns.jcp.org/xml/ns/persistence" x Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/persisten Ce http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd "version=" 2.1 "&
    Gt <!--has one or more persistence-unit--> <!--transaction-type: The default is JTA (Java transaction API) in the EE application server. Default to Standard local transaction resource_local in J2SE and simple servlet containers. To avoid ambiguity, we should explicitly set--> <!--persistence-unit inside can be empty, but if set, must order--> <persistence-unit name= "entitymappingst Est "transaction-type=" resource_local > <!--first is <description> small example does not provide--> <!--provider: With The Javax.persistence.spi.PersistenceProvider implementation of the body, the default value is the implementation of the first JPA in Classpath--> <provider> Org.hibernate.jpa.hibernatepersistenceprovider</provider> <!--If the transaction-type of Persistence-unit is JTA, Using &LT;JTA-data-source&gt, if for resource_local, use <non-jta-data-source>. The difference is that the latter uses the Entitytransaction interface, and the former uses the UserTransaction interface, which defaults to the former (JTA). They all take the form of Jndi (Java naming and Directory Interface) and give the data source. --> <non-jta-data-source>java:comp/env/jdbc/learnTest</non-jta-data-source> <!--<map Ping-file&gt: classpath-based XML mapping file, if not specified, the default is Orm.xml, you can set multiple Mapping-file--> <!--&LT;JAR-FILE&GT;:JPA Implementation will bind the jar package to the tag scan, if there are @entity, @Embeddable, @javax. Persistence.mappedsuperclass or @ Javax.persistence.Converter, added to this continuation unit, you can set up multiple Jar-file--> <!--&LT;CLASS&GT;:JPA implementation will add this class to the persistence unit, this class Must carry @entity, @Embeddable, @javax. Persistence.mappedsuperclass or @javax.persistence.converter. You can set multiple class--> <!--settings <exclude-unlisted-classes/> or <exclude-unlisted-classes>true</exclude- Unlisted-classes> says that only focus on the Jar-file and set in class, do not scan the other. Delete <exclude-unlisted-classes/> or &LT;EXCLUDE-UNLISTED-CLASSES&GT;FALSE&LT;/EXCLUDE-UNLISTED-CLASSES&Gt; the classpath location is scanned, if the file is in a jar file, the classes of the jar file is scanned, and if the file is located in a specific directory in classes, only files in that directory (for example, to a package) are scanned. --> <exclude-unlisted-classes>false</exclude-unlisted-classes> <!--<shared-cache-mod E&gt: Cache entity,--> <!--➤none indicates that the,--> <!--is not cached to indicate that all ➤all are cached. --> <!--➤enable_selective indicates that only entity--> <!--with @cacheable or @cacheable (true) identities are cached ➤disable_se Lective means that except @cacheable (false) all cache--> <!--➤unspecified represents a JPA provider to decide, Hibernate ORM defaults to Enable_selective, but uses this Way, there may be confusion about the transplant, you should explicitly set--> <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <!--& Lt;validation-mode>--> <!--➤none means not to use the Bean validator,--> <!--➤callback representation in the write operation (insert,upd
        Ate,delete) before validate--> <!--➤auto, if there is a bean classpath validator in the provider, then callback, none exists--> <!--If you use validate, and we customize the VALIDATOR,JPA of the spring framework, this customization will be ignored. BecauseThis recommendation uses none to validate data before it is persisted, rather than at the level of persistence. --> <validation-mode>NONE</validation-mode> <!--<properties> provide other JPA in a name-value manner attributes (such as JDBC connections, users, passwords, schema generation, etc.) and provider-specific properties such as hibernate settings. --> <properties> <!--prohibit schema generation, that is, do not create tables based on entity--> <property Name= "Java X.persistence.schema-generation.database.action "value=" None "/> </properties> </persistence-unit&
Gt </persistence>

Persistent Code We use the servlet example to show how to query tables and insert tables.

@WebServlet (name = "Entityservlet", Urlpatterns = "/entities", Loadonstartup = 1) public class Entityservlet E
    Xtends HttpServlet {private static final long serialversionuid = 1L;
    Private final Random Random;
       
    Entity Manager: Acquired at initialization, at the end is closed private entitymanagerfactory factory;
        Public Entityservlet () {super ();
        try {this.random = Securerandom.getinstancestrong ();
        catch (NoSuchAlgorithmException e) {throw new IllegalStateException (e); }/** "1.1" creates entitymanagerfactory on initialization.
      The name of the continuity unit is persistence.xml. * For full Java EE server (tomcat is not), this is not required, using: * @PersistenceContext ("entitymappingstest") * entitymanagerfactory F Actory;
        * * @Override public void init () throws Servletexception {Super.init ();
    This.factory = Persistence.createentitymanagerfactory ("Entitymappingstest"); /** "1.2" closes entitymanagerfactory/@Override public void des at the endTroy () {this.factory.close ();
    Super.destroy (); /** "2" we demonstrated in doget to get the table contents, which demonstrated the general code for transaction processing/protected void doget (HttpServletRequest request, Httpser
        Vletresponse response) throws Servletexception, IOException {Entitymanager manager = null;
        Entitytransaction transaction = NULL;
            try{manager = This.factory.createEntityManager ();
            Transaction = Manager.gettransaction ();

            Transaction.begin (); Read the table publisher (simple Full access method) Criteriabuilder builder = Manager.getcriteriabuilder ();//Return to Criteriaq			
            The Criteriabuilder instance of Uery objects criteriaquery<publisher> q1 = builder.createquery (Publisher.class);
            root<publisher> q1root = Q1.from (Publisher.class);
            Typedquery<publisher> QueryResult = Manager.createquery (Q1.select (q1root));

           Request.setattribute ("Publishers", Queryresult.getresultlist ()); Read the table Author (simply using the full access method) criteriaquery<author> q2 = Builder.createquery (Author.class);

            Request.setattribute ("Authors", Manager.createquery (Q2.select (Q2.from (Author.class))), getresultlist ());
            criteriaquery<book> q3 = builder.createquery (Book.class);

            Request.setattribute ("Books", Manager.createquery (Q3.select (Q3.from (Book.class))). Getresultlist ());
            Transaction.commit ();			
        Request.getrequestdispatcher ("/web-inf/jsp/view/entities.jsp"). Forward (request, response); }catch (Exception e) {if (transaction!= null && transaction.isactive ()) Transaction.rol
            Lback (); E.printstacktrace (Response.getwriter ()); Simply in the page output, the formal item will not be handled}finally{if (manager!= null && manager.isopen ()) Manage
        R.close (); }/** "3" We demonstrate insert/protected void DoPost in DoPost (httpservletrequest request, HttpservletresPonse response) throws Servletexception, IOException {Entitymanager manager = null;
        Entitytransaction transaction = NULL;
            try{manager = This.factory.createEntityManager ();
            Transaction = Manager.gettransaction ();

            Transaction.begin ();
            Publisher publisher = new publisher ();
            Publisher.setname ("John Wiley & Sons");
            Publisher.setaddress ("1234 Baker Street");

            Manager.persist (publisher);
            Author Author = new Author ();
            Author.setname ("Nicholas S. Williams");
            Author.setemailaddress ("nick@example.com");

            Manager.persist (author);
            Book book = new book ();
            BOOK.SETISBN ("" + this.random.nextInt (integer.max_value));
            Book.settitle ("Professional Java for Web applications");
            Book.setauthor ("Nicholas S. Williams");
            Book.setpublisher ("John Wiley & Sons"); Book.setprice (59.99D);

            Manager.persist (book);
            Transaction.commit ();
        Response.sendredirect (Request.getcontextpath () + "/entities"); }catch (Exception e) {if (transaction!= null && transaction.isactive ()) Transaction.rol
            Lback ();
        E.printstacktrace (Response.getwriter ());
        }finally{if (manager!= null && manager.isopen ()) manager.close (); }
    }
}

RELATED links: My professional Java for WEB applications related articles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.