Simple and quick integration with springboot JDBC

Source: Internet
Author: User
Continue to follow the rhythm of the previous section, simple and fast integration of JDBC 

First import jdbc and MySQL springboot jar files

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId> mysql-connector-java</artifactid>
        </dependency>

        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactid>spring-boot-starter-jdbc </artifactId>
        </dependency>

You also need to configure the following code in Application.properties:

Database connection address, port number, connection name, setting encoding format
spring.datasource.url=jdbc:mysql://localhost:3306/test?autoreconnect=true& Useunicode=true&characterencoding=utf-8/
/username
spring.datasource.username=root
//password
Spring.datasource.password=root
//Database driver
spring.datasource.driver-class-name=com.mysql.jdbc.driver
This is my file location, name screenshot:

In the new entity file, build a studententity test entity class inside it:

public class Studententity {//ID private Integer ID;
    Name private String name;
    Age private Integer;
    gender private String sex;
    Address private String addresses;

    Whether tombstone (0: not deleted, 1: deleted) private Integer isdelete;
    Public Integer GetId () {return id;
    The public void SetId (Integer id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public Integer Getage () {return age;
    public void Setage (Integer age) {this.age = age;
    Public String Getsex () {return sex;
    } public void Setsex (String sex) {this.sex = sex;
    Public String getaddress () {return address;
    public void setaddress (String address) {this.address = address;
    Public Integer Getisdelete () {return isdelete; } public void Setisdelete(Integer Isdelete)
    {this.isdelete = Isdelete;
 }
}

Down directly to the service, create the Studentservice interface code as follows:

Public interface Studentservice {

    //write Data
    int savestudent ();

    Query data
    list<studententity> queryallstudent ();

    Update Data
    int updatestudent (studententity studententity);

    Delete data
    int deletestudent (Integer ID);


Also create Impl file, Studentserviceimpl class, code as follows:

Import com.demo.entity.StudentEntity;
Import Com.demo.mapper.StudentMapper;
Import Com.demo.service.StudentService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.core.PreparedStatementSetter;
Import Org.springframework.jdbc.core.RowMapper;

Import Org.springframework.stereotype.Service;
Import Javax.annotation.Resource;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import java.util.List; @Service ("studentservices")/Alias public class Studentserviceimpl implements Studentservice {@Resource private Jd


    Bctemplate JdbcTemplate;
        JDBC writes data @Override public int savestudent () {//initialization attribute parameter String name = "John";
        Integer age = 12;
       Execute write int row = Jdbctemplate.update ("INSERT into student (name,age) VALUES (?,?);", "Dick", 12);
    Returns the result return row; //JDBC Query Data @OverridE public list<studententity> queryallstudent () {//sql String SQL = ' select * FROM student wher
        E is_delete=0 "; Results list<studententity> List = jdbctemplate.query (sql, new rowmapper<studententity> () {/
                /map per row of data @Override public studententity Maprow (ResultSet rs, int rownum) throws SQLException {
                Studententity stu = new studententity ();
                Stu.setid (Rs.getint ("ID"));
                Stu.setage (Rs.getint ("Age"));
                Stu.setname (rs.getstring ("NAME"));
                Stu.setaddress (rs.getstring ("Address"));
            return Stu;
        }

        });
    Returns the result return list; //JDBC Update Data @Override public int updatestudent (studententity studententity) {//sql String sql = "Update tudent set name=?,address=?"
        where id=? "; result int row = jdbctemplate.update (sql, New PreparedStatementSetter () {//Map data @Override public void Setvalues (PreparedStatement preparedstatement) throws
                SQLException {preparedstatement.setstring (1, Studententity.getname ());
                Preparedstatement.setstring (2, studententity.getaddress ());
            Preparedstatement.setint (3, Studententity.getid ());
        }
        });
    The result return row; }//delete data @Override public int deletestudent (Integer id) {//sql+ result int resrow = JdbcTemplate. Update ("Update student SET is_delete=1 WHERE id=?", new PreparedStatementSetter () {//Mapping data @Overri
            De public void setvalues (PreparedStatement PS) throws SQLException {Ps.setint (1, id);
        }
        });
    Returns the result return resrow;

 }
}

The

ends with controller, creating Studentcontrollerimpl: Code as follows

Import com.demo.entity.StudentEntity;
Import Com.demo.service.StudentService;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RestController;
Import Javax.annotation.Resource;
Import java.util.ArrayList;
Import Java.util.Iterator;

Import java.util.List;

    @RestController public class Studentcontrollerimpl {@Autowired private studentservice studentservices; /** * NEW Data * * */@RequestMapping ("/save") public String Save () {int row = Studentservices.savestu
       Dent ();
        Judgment result if (row==-1) {return "new failure";
        }else{return "new success"; }/** * Query data */@RequestMapping ("/query") public String query () {//Lookup data Lis
        T list = Studentservices.queryallstudent ();
        Assembly data List NewList = new ArrayList (); Loop out result for (int i = 0; I <list.size ();
            i++) {//New Student object studententity stu = (studententity) list.get (i);
            Fill Data Newlist.add (Stu.getid ());
            Newlist.add (Stu.getname ());
            Newlist.add (Stu.getage ());
            Newlist.add (Stu.getsex ());
        Newlist.add (Stu.getaddress ());
    //Return the data Back newlist.tostring (); /** * UPDATE Data * */@RequestMapping ("/update") public String Update () {//New object delivery data St
        Udententity stu = new studententity ();
        Stu.setid (2);
        Stu.setname ("Nicholas");
        Stu.setaddress ("Northeast");
        Perform an update operation int row = Studentservices.updatestudent (stu);
        Judgment result if (row==-1) {return "update failed";
        }else {return "successful update";
        }/** * Delete data * */@RequestMapping ("/delete") public String Delete () {//Initialize data
        Integer id = 3; Execute Delete int row = StudentseRvices.deletestudent (ID);
        Judgment result if (row==-1) {return "delete failed";
        }else{return "Delete Success";
 }
    }
}
 This is done, start running my url:localhost:8080/save, please pass the great God a lot of advice, if you have questions or questions please leave a message, 

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.