好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

一小时迅速入门Mybatis之Prepared Statement与符号的使用

引入Mysql的Jar包以及表结构前几篇已经有了这里就不赘述了

一、用一用 PreparedStatement

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

import java.math.BigDecimal;

import java.sql.*;

 

/**

  * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作

  * @create 2021-08-25 21:26

  */

public class TestMain {

     public static void main(String[] args) throws Exception {

         Connection conn = null ;

         PreparedStatement stmt = null ;

         ResultSet result = null ;

         try {

             // 1. 注册驱动

             Class.forName( "com.mysql.jdbc.Driver" );

             // 2. 打开连接 url 、 用户名、 密码

             conn = DriverManager.getConnection(

                     "jdbc:mysql://127.0.0.1:3306/test?useSSL=false" ,

                     "root" ,

                     "123456" );

             // 3. 创建Statenebt

             stmt = conn.prepareStatement( "select * from test where name = ?" );

             // 4. 设置参数 注意啦,参数下标是从1开始的 不是0哦

             stmt.setString( 1 , "小强" );

             // 5. 执行查询

             result = stmt.executeQuery();

             // 6. 输出数据库获取的结果

             while (result.next()){

                 // 根据列名称获取值

                 String name = result.getString( "name" );

                 BigDecimal salary = result.getBigDecimal( "salary" );

                 System.out.println(name+ " 的工资是:" +salary);

             }

 

         } catch (Exception e) {

             e.printStackTrace();

         } finally {

             // 关闭资源

             // 关闭资源

             try {

                 if (result!= null ) {

                     result.close();

                 }

             } catch (SQLException se2){

                 System.err.println( "关闭result异常" );

             }

             try {

                 if (stmt!= null ) {

                     stmt.close();

                 }

             } catch (SQLException se2){

                 System.err.println( "关闭stmt异常" );

             }

             try {

                 if (conn!= null ) {

                     conn.close();

                 }

             } catch (SQLException se){

                 System.err.println( "关闭conn异常" );

             }

         }

 

     }

}

二、用一用 Statement

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

import java.math.BigDecimal;

import java.sql.*;

 

/**

  * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作

  */

public class TestMain02 {

     public static void main(String[] args) throws Exception {

         Connection conn = null ;

         Statement stmt = null ;

         ResultSet result = null ;

         try {

             // 1. 注册驱动

             Class.forName( "com.mysql.jdbc.Driver" );

             // 2. 打开连接 url 、 用户名、 密码

             conn = DriverManager.getConnection(

                     "jdbc:mysql://127.0.0.1:3306/test?useSSL=false" ,

                     "root" ,

                     "123456" );

             // 3. 创建Statenebt

             stmt = conn.createStatement();

             // 4. 执行查询

             result = stmt.executeQuery( "select * from test where name = '小强'" );

             // 5. 输出数据库获取的结果

             while (result.next()){

                 // 根据列名称获取值

                 String name = result.getString( "name" );

                 BigDecimal salary = result.getBigDecimal( "salary" );

                 System.out.println(name+ " 的工资是:" +salary);

             }

 

         } catch (Exception e) {

             e.printStackTrace();

         } finally {

             // 关闭资源

             // 关闭资源

             try {

                 if (result!= null ) {

                     result.close();

                 }

             } catch (SQLException se2){

                 System.err.println( "关闭result异常" );

             }

             try {

                 if (stmt!= null ) {

                     stmt.close();

                 }

             } catch (SQLException se2){

                 System.err.println( "关闭stmt异常" );

             }

             try {

                 if (conn!= null ) {

                     conn.close();

                 }

             } catch (SQLException se){

                 System.err.println( "关闭conn异常" );

             }

         }

 

     }

}

三、Mybatis #{} ${} 的使用

#{}使用

?

1

2

// #{}  根据名称查询数据

List<TestEntity> listByName01(String name);

?

1

2

3

4

<! --#{} 查询数据-->

< select id= "listByName01" resultType= "testentity" >

     select * from test where name = #{ name }

</ select >

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import dao.TestMapper;

import entity.TestEntity;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

import java.util.List;

 

/**

  * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作

  */

public class TestMain03 {

     public static void main(String[] args) throws Exception {

         String resource = "mybatis-config.xml" ;

         InputStream inputStream = Resources.getResourceAsStream(resource);

         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

         try (SqlSession session = sqlSessionFactory.openSession()) {

             // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper

             TestMapper mapper = session.getMapper(TestMapper. class );

             // 1.#{}

             List<TestEntity> res = mapper.listByName01( "小强" );

             // 这个执行的sql : select * from test where name = '小强 '

             System.out.println( "第一次查询条数:" +res.size());

             List<TestEntity> res02 = mapper.listByName01( "小强  or 1=1" );

             // 这个执行的sql: select * from test where name = '小强  or 1=1'

             System.out.println( "第二次查询条数:" +res02.size());

         }

     }

}

${}使用

?

1

2

// ${}  根据名称查询数据

List<TestEntity> listByName02( @Param ( "name" ) String name);

?

1

2

3

4

<! --${} 查询数据-->

< select id= "listByName02" resultType= "testentity" >

     select * from test where name = ${ name }

</ select >

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import dao.TestMapper;

import entity.TestEntity;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

 

import java.io.InputStream;

import java.util.List;

 

/**

  * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作

  */

public class TestMain04 {

     public static void main(String[] args) throws Exception {

         String resource = "mybatis-config.xml" ;

         InputStream inputStream = Resources.getResourceAsStream(resource);

         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

         try (SqlSession session = sqlSessionFactory.openSession()) {

             // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper

             TestMapper mapper = session.getMapper(TestMapper. class );

             // 1.${} 这里还得自己加个单引号 要不然sql就不对了

             List<TestEntity> res = mapper.listByName02( "'小强'" );

             // 执行的sql: select * from test where name = '小强'

             System.out.println( "第一次:" +res.size());

             List<TestEntity> res02 = mapper.listByName02( "'小强 ' or 1=1 " );

             // 执行的sql(可怕哦): select * from test where name = '小强 ' or 1=1

             System.out.println( "第二次:" +res02.size());

         }

     }

}

#{} 使用的是PrepareStatment 用的是 ‘?' 占位符 不会被SQL注入 不管你输出什么都会给你用单引号包起来

类似这种:

?

1

2

3

4

5

6

7

8

9

public class TestMain05 {

     public static void main(String[] args)   {

         String sql = "select * from test where name = '?' " ;

         String name = "小强" ;

         sql = sql.replace( "?" , name);

         System.out.println(sql);

         // select * from test where name = '小强'

     }

}

${} 他就相当于是普通的拼接 你传入什么就原封不动的给你放到Sql后边

类似这种:

?

1

2

3

4

5

6

7

8

public class TestMain06 {

     public static void main(String[] args)   {

         String sql = "select * from test where name = ?" ;

         String name = "'小强'" ;

         sql = sql.replace( "?" , name);

         System.out.println(sql);

     }

}

四、ResultMap ResultType的区别

resultType使用方式我们已经用过很多次了,这里先下一个resultMap的使用方式

?

1

2

3

4

5

6

7

8

9

10

< resultMap id = "testResultMap" type = "testentity" >

     < id property = "id" column = "id" javaType = "long" jdbcType = "BIGINT" />

     < result property = "name" column = "name" javaType = "string" jdbcType = "VARCHAR" />

     < result property = "age" column = "name" javaType = "int" jdbcType = "INTEGER" />

     < result property = "salary" column = "name" javaType = "decimal" jdbcType = "DECIMAL" />

  </ resultMap >

 

  < select id = "testResultMap" resultMap = "testResultMap" >

     select * from test

  </ select >

resultType、resultMap功能类似,都是返回对象信息,但是resultMap要更强大一些,可以实现自定义。

我们一般项目中数据库都是下划线比如course_date 但是实体类中都是用courseDate 所以大部分时候都需要进行名称匹配都会用到resultMap 或者 sql写别名

sql别名方式:

?

1

2

3

4

5

6

7

8

< select id = "list" resultType = "testentity" >

     select

     id as id

     name as name

     age as age

     course_date as courseDate

     from test

</ select >

id&result

他俩都是将一列值映射到一个简单的数据类型(String、int、double、Date等)的属性或字段。

他俩唯一的不同是:id元素对应的属性会被标记为对象的标识符,在比较对象实例的时候使用。这样可以提升整体的性能,尤其是进行缓存和嵌套结果映射的时候。

他俩都有一些属性:

 

属性 描述
property 映射到列结果的字段或属性
column 数据库中的列名,或者是列的别名。一般情况下,这和传递给 resultSet.getString(columnName) 方法的参数一样。
就是数据库列名
javaType 一个 Java 类的全限定名,或一个类型别名 如果你映射到一个 JavaBean,MyBatis 通常可以推断类型。然而,如果你映射到的是 HashMap,那么你应该明确地指定 javaType 来保证行为与期望的相一致。
jdbcType 这就是数据库对应的类型,非必须的
typeHandler 结果处理器,就是把结果再处理一次返回 后边几篇写一下自定义typeHandler

 

在中文官网上找了个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<!-- 非常复杂的结果映射 -->

< resultMap id = "detailedBlogResultMap" type = "Blog" >

   < constructor >

     < idArg column = "blog_id" javaType = "int" />

     < arg   column = "name" javaType = "varchar" ></ arg >

   </ constructor >

   < result property = "title" column = "blog_title" />

   < association property = "author" javaType = "Author" >

     < id property = "id" column = "author_id" />

     < result property = "username" column = "author_username" />

     < result property = "password" column = "author_password" />

     < result property = "email" column = "author_email" />

     < result property = "bio" column = "author_bio" />

     < result property = "favouriteSection" column = "author_favourite_section" />

   </ association >

   < collection property = "posts" ofType = "Post" >

     < id property = "id" column = "post_id" />

     < result property = "subject" column = "post_subject" />

     < association property = "author" javaType = "Author" />

     < collection property = "comments" ofType = "Comment" >

       < id property = "id" column = "comment_id" />

     </ collection >

     < collection property = "tags" ofType = "Tag" >

       < id property = "id" column = "tag_id" />

     </ collection >

     < discriminator javaType = "int" column = "draft" >

       < case value = "1" resultType = "DraftPost" />

     </ discriminator >

   </ collection >

</ resultMap >

constructor: 用于实例化类时,注入结果到构造方法中

​ idArg:这个就是主键ID

​ arg:这个就是普通字段

association: 一个复杂类型的关联 对象里字段是对象

collection:一个复杂的类型关联 对象里字段是集合

discriminator: 使用结果值来确认使用哪个resultMap

下集预告:

写一个复杂点的返回结果resultMap案例

动态SQL 常用标签

到此这篇关于一小时迅速入门Mybatis之Prepared Statement与符号的使用的文章就介绍到这了,更多相关Mybatis Prepared Statement内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_36291682/article/details/119983969

查看更多关于一小时迅速入门Mybatis之Prepared Statement与符号的使用的详细内容...

  阅读:12次