Using IntelliJ idea to develop SPRINGMVC website (iii) database configuration

Source: Internet
Author: User
Tags import database

Note: Before reading this article, please read:

Develop SPRINGMVC website using IntelliJ idea (i) Development environment

Using IntelliJ idea to develop SPRINGMVC website (ii) framework Configuration


Vi. Database Configuration

Here's a simple example of how SPRINGMVC integrates spring data JPA (provided by Hibernate JPA) for powerful database access and is explained in this section Get a deeper understanding of how the controller handles request processing, and believe that you can start your development work by reading this section.

preparatory work:

Create a new two package in Src\main\java: Com.gaussic.model, Com.gaussic.repository, will be used later.

1. Create MySQL Database

This article explains the use of MySQL database, if you use other database readers, you can go to the web to refer to other configuration tutorials, do not do too much narration here. The database is an underlying thing, and the underlying details have little effect on the abstraction of the upper layer, so as long as the database is configured, the content of this chapter is still applicable to all databases (seemingly so).

Let's say we're going to build a small blogging system, and the database ER diagram looks like this (and of course it's just a small example of how much more complicated the real blogging system is):

In the database, there are two tables:

(1) User table users: Store the user's login information, the primary key ID is set to self-increment;

(2) blog post Table blog: Save the user post, the primary key ID is set to self-increment, there is a foreign key userid link to the user table.

The detailed table structure looks like this:

2. IntelliJ Idea Import Database

For some of the commonly used frameworks that have come into contact, a single data table often corresponds to a Java Bean. In Springmvc, this Java bean is equivalent to model. So, does this class need to be written by itself? No, using IntelliJ idea can help us generate these javabean automatically.

First, right-click the project and select Add Framework support:

Drop-down select Java EE persistence, right provider select Hibernate,libraries Select Set up later (Maven has imported the required jar packages):

At the end of this step, we can find that the Persistence.xml configuration file is generated in the resources, and a persistence title appears in the left column (if not, click the gray box in the lower left corner):

Persistemce.xml specific as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><persistence xmlns= "Http://java.sun.com/xml/ns/persistence" version = "2.0" > <persistence-unit name= "newpersistenceunit" > <provider>org.hibernate.ejb.hibernatepersist            ence</provider> <properties> <property name= "Hibernate.connection.url" value= "/> <property name= "Hibernate.connection.driver_class" value= ""/> <property name= "Hibernate.connect Ion.username "value=" "/> <property name=" Hibernate.connection.password "value=" "/> <prop Erty name= "Hibernate.archive.autodetection" value= "class"/> <property name= "Hibernate.show_sql" value= "tr  UE "/> <property name=" Hibernate.format_sql "value=" true "/> <property name=" Hbm2ddl.auto " value= "Update"/> </properties> </persistence-unit></persistence>

Let's not worry about filling out this configuration file first. Click the persistence in the left column to display the following:

Right-click the project name, select Generate Persistence Mapping, and select by Database Schema:

The following interface appears, where the main needs to be configured are as shown in the red box:

Click on the three points to the right of choose Data Source to select the DataSource, select "+" in the upper left corner of the popup screen and select MySQL:

In the following interface to fill in the host, port number, database name, user name, password, if the driver is lost click on the following download can download the driver, click Test Connection can test the database is connected successfully:

After the above interface configuration is complete, click OK, go back to the following page, package fill out the Model (1), tick show default relationships to show all database relations (2), and then click the Refresh button (3), will find the database of two tables, Expand two tables and select All (4, except for foreign keys), tick generate column defination to generate the description information for each column (5), click OK, and choose Yes.

Later, opening the model package, you can see that two Java beans were generated, called two entities in Springmvc, that correspond to the two tables of the database:

The blogentity is as follows:

Package Com.gaussic.model;import javax.persistence.*;/** * Created by Dzkan on 2015/10/4.    */@Entity @table (name = "Blog", schema = "", Catalog = "Springdemo") public class Blogentity {private int id;    Private String title;    Private String content;    Private Userentity Userbyuserid; @Id @Column (name = "Id", nullable = False, Insertable = true, updatable = true) public int getId () {return I    D    } public void setId (int id) {this.id = ID; } @Basic @Column (name = "title", Nullable = True, Insertable = true, updatable = true, length =) public Strin    G GetTitle () {return title;    public void Settitle (String title) {this.title = title; } @Basic @Column (name = "Content", Nullable = True, Insertable = true, updatable = true, length = 255) Public Str    ing getcontent () {return content;    The public void SetContent (String content) {this.content = content; } @Override public boolean equals (ObJect o) {if (this = O) return true;        if (o = = NULL | | getclass ()! = O.getclass ()) return false;        Blogentity that = (blogentity) o;        if (id! = that.id) return false;        if (title! = null?!title.equals (that.title): That.title! = null) return false;        if (content! = null?!content.equals (that.content): That.content! = null) return false;    return true;        } @Override public int hashcode () {int result = ID;        result = * result + (title! = null? Title.hashcode (): 0);        result = * result + (content! = null? Content.hashcode (): 0);    return result; } @ManyToOne @JoinColumn (name = "UserID", referencedcolumnname = "id", nullable = False) public userentity Getuse    Rbyuserid () {return userbyuserid;    } public void Setuserbyuserid (Userentity userbyuserid) {this.userbyuserid = Userbyuserid; }}

As we can see, in blogentity, not only does it contain all of its columns, but it also generates one more:

Private Userentity Userbyuserid;

In Springmvc, you can use this class as a foreign key for foreign key related operations, how the specific usage will be explained later.

See Userentity again:

Package Com.gaussic.model;import javax.persistence.*;import java.util.collection;/** * Created by Dzkan on 2015/10/4.    */@Entity @table (name = "User", schema = "", Catalog = "Springdemo") public class Userentity {private int id;    Private String FirstName;    Private String LastName;    private String password;    Private collection<blogentity> Blogsbyid; @Id @Column (name = "Id", nullable = False, Insertable = true, updatable = true) public int getId () {return I    D    } public void setId (int id) {this.id = ID; } @Basic @Column (name = "FirstName", nullable = True, Insertable = true, updatable = true, length =) public St    Ring Getfirstname () {return firstName;    } public void Setfirstname (String firstName) {this.firstname = FirstName; } @Basic @Column (name = "LastName", nullable = True, Insertable = true, updatable = true, length =) public Str    ing Getlastname () {return lastName; } public voidSetlastname (String lastName) {this.lastname = LastName; } @Basic @Column (name = "Password", nullable = True, Insertable = true, updatable = true, length =) public Str    ing GetPassword () {return password;    } public void SetPassword (String password) {this.password = password;        } @Override public boolean equals (Object o) {if (this = = O) return true;        if (o = = NULL | | getclass ()! = O.getclass ()) return false;        Userentity that = (userentity) o;        if (id! = that.id) return false;        if (firstName! = null?!firstname.equals (that.firstname): That.firstname! = null) return false;        if (lastName! = null?!lastname.equals (that.lastname): That.lastname! = null) return false;        if (password! = null?!password.equals (That.password): That.password! = null) return false;    return true;        } @Override public int hashcode () {int result = ID; result = * result + (FirstName! = null?) Firstname.hashcode (): 0);        result = * result + (LastName! = null? Lastname.hashcode (): 0);        result = * result + (password! = null? Password.hashcode (): 0);    return result; } @OneToMany (Mappedby = "Userbyuserid") public collection<blogentity> Getblogsbyid () {return Blogsbyid    ;    } public void Setblogsbyid (collection<blogentity> blogsbyid) {This.blogsbyid = Blogsbyid; }}

It also generates:

Private collection<blogentity> Blogsbyid;

The same is to meet the foreign key requirements.

3. Configuration database

Now that the database has been imported, the preparatory work is basically complete and the final configuration is required.

First, open Mvc-dispatcher-servlet.xml and add the following configuration (select and press ALT + INSERT to complete the configuration if there are errors in some places):

<!--means the package--><jpa:repositories base-package= "com.gaussic.repository"/><bean id= "in which the JPA repository is located Entitymanagerfactory "class=" Org.springframework.orm.jpa.LocalEntityManagerFactoryBean ">    <property Name= "Persistenceunitname" value= "Defaultpersistenceunit"/></bean><!--transaction management--><bean id= " TransactionManager "class=" Org.springframework.orm.jpa.JpaTransactionManager ">    <property name=" Entitymanagerfactory "ref=" entitymanagerfactory "/></bean><tx:annotation-driven transaction-manager=" TransactionManager "/>

Explain:

(1) Jpa:repositories: This part relates to the interface of the database, which will be explained in detail later;

(2) Entitymanagerfactory: Entity Manager factory, read Persistence.xml configuration;

(3) TransactionManager: Transaction manager, using Entitymanager for transaction management;

(4) Tx:annotation-driven: Open the note driver for the transaction manager, you can manipulate the database by using annotations.

The whole is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:       Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns:jpa= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA "xmlns:tx=" Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schem A/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/con Text Http://www.springframework.org/schema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MV       C Http://www.springframework.org/schema/mvc/spring-mvc.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA Http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http: www.springframework.org/schema/Tx/spring-tx.xsd "> <!--Specify the controller's package and scan for annotations--<context:component-scan base-package=" Com.gaussic. Controller "/> <!--static resources (JS, image, etc.) Access--<mvc:default-servlet-handler/> <!--turn on annotations--&L T;mvc:annotation-driven/> <!--viewresolver View Parser--<!--to support Servlet, JSP view resolution--<bean id= "Jspvie Wresolver "class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" Viewclass "value=" Org.springframework.web.servlet.view.JstlView "/> <property name=" prefix "value="/web-inf/p    ages/"/> <property name=" suffix "value=". jsp "/> </bean> <!--represents the package of JPA repository <jpa:repositories base-package= "Com.gaussic.repository"/> <bean id= "entitymanagerfactory" class= " Org.springframework.orm.jpa.LocalEntityManagerFactoryBean "> <property name=" persistenceunitname "value=" Defaultpersistenceunit "/> </bean> <! --Transaction management--<bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManager" > &L T;property name= "Entitymanagerfactory" ref= "entitymanagerfactory"/> </bean> <tx:annotation-driven Trans Action-manager= "TransactionManager"/></beans>

    , fill persistence.xml, change the name of Persistence-unit to Defaultpersistenceunit. In the following file, I added some more detailed configuration:

<?xml version= "1.0" encoding= "UTF-8"? ><persistence xmlns= "Http://java.sun.com/xml/ns/persistence" version = "2.0" > <persistence-unit name= "defaultpersistenceunit" transaction-type= "resource_local" > <provide             R>org.hibernate.ejb.hibernatepersistence</provider> <properties> <!--using MySQL dialect--- <property name= "Hibernate.dialect" value= "Org.hibernate.dialect.MySQL5Dialect"/> <!--database connection URL--<property name= "Hibernate.connection.url" value= "Jdbc:mysql://localhost: 3306/springdemo "/> <!--database Connection driver--<property name=" Hibernate.connection.driver_class " Value= "Com.mysql.jdbc.Driver"/> <!--the user name of the database connection--<property name= "hibernate.connection. Username "value=" root "/> <!--database connection password--<property name=" Hibernate.connection.password "Value=" root "/> <! --Show SQL statement--<property name= "Hibernate.show_sql" value= "true"/> <property name= "Hibern Ate.connection.useUnicode "value=" true "/> <property name=" hibernate.connection.characterEncoding "value="             UTF-8 "/> <!--formatting statements when displaying SQL statements--<property name=" Hibernate.format_sql "value=" true "/>            <property name= "Hibernate.use_sql_comments" value= "false"/> <!--Auto Output schema to create DDL statements--            <property name= "Hibernate.hbm2ddl.auto" value= "Update"/> <!--the database connection times out and automatically re-connects <property name= "Hibernate.connection.autoReconnect" value= "true"/> <property name= "Connection.autore Connectforpools "value=" true "/> <property name=" connection.is-connection-validation-required "value=" true "/> </properties> </persistence-unit></persistence>

Now, to restart Tomcat, if there is no error, the database has been configured to complete, the next step is to explain the database related development work.

Using IntelliJ idea to develop SPRINGMVC website (iii) database configuration

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.