欢迎光临散文网 会员登陆 & 注册

Mybatis框架映射,一对多或一对一地打印数据,Oracle动态SQL处理,个人详细注释和单词

2021-03-13 16:11 作者:诗书画唱  | 我要投稿

本期的重点:

单词意思

包含个人详细注释的例子(几乎无障碍阅读)

1.Mybatis框架实现组合查询和分页查询

2.一对多地打印数据,一对一地打印数据


留给读者的作业(很容易和我提供详细注释的例子相似) 


--查询userinfo表,根据act进行模糊查询

--如果没有输入账号,就查询所有

--如果输入了账号,就进行模糊查询


--查询userinfo表,根据act和日期进行查询

--每次查询只使用一个条件,要么根据账号进行查询,

--要么根据日期进行查询,这两个条件是互相排斥的


--组合查询

--act模糊查询

--pwd精确匹配

--brith范围查询


--分页查询

--page当前页码

--rows每页显示记录条数

--end = page * rows【end代表<=后面的数值】

--start = (page - 1) * rows + 1【start代表>=前面的数值】


包含个人详细注释的例子(几乎无障碍阅读)START



1.Mybatis框架实现组合查询和分页查询


Mybatis框架建表示例 START


 --drop table Userinfo                

create table Userinfo(

    id number primary key,

    act varchar2(30) not null,

   pwd varchar2(30) not null,

   birth date

);


--drop sequence seq_Userinfo

create sequence seq_Userinfo

start with 1       --起始值是1

increment by 1     --增长的值   

maxvalue 999999999 --序列号的最大值

minvalue 1         --序列号的最小值

nocycle            --是否循环

cache 10;          --预存



insert into Userinfo values(seq_Userinfo.nextval,'黑黑','pwd1',to_date('2020-06-06','yyyy-mm-dd'));

insert into Userinfo values(seq_Userinfo.nextval,'红红','pwd2',to_date('2020-06-07','yyyy-mm-dd'));

insert into Userinfo values(seq_Userinfo.nextval,'蓝蓝','pwd3',to_date('2020-06-08','yyyy-mm-dd'));

insert into Userinfo values(seq_Userinfo.nextval,'诗书画唱','pwd4',to_date('2020-06-06','yyyy-mm-dd'));

insert into Userinfo values(seq_Userinfo.nextval,'三连','pwd5',to_date('2020-06-10','yyyy-mm-dd'));

insert into Userinfo values(seq_Userinfo.nextval,'关注','pwd6',to_date('2020-06-11','yyyy-mm-dd'));

--select * from Userinfo



--rows=5,page=2

--end = rows * page=10

--start = (page - 1) * rows + 1=6

--start表示>=好后面的值,end表示<=号后面的值


 select * from

(select p1.*,rownum r1 from Userinfo p1

where rownum <= 10)

where r1 >=6



Mybatis框架建表示例 END

package com.SSHC.bean;


public class Userinfo {

    private Integer id;

    private String act;

    private String pwd;

    private String birth;

    //查询属性

    private String begin;//开始日期

    private String end;//截至日期

    

    //通用的分页属性

    private Integer page;//当前显示第几页的数据

    private Integer rows;//每页显示的记录条数

    

    //oracle分页属性

    private Integer pstart;

    private Integer pend;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getAct() {

return act;

}

public void setAct(String act) {

this.act = act;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

public String getBirth() {

return birth;

}

public void setBirth(String birth) {

this.birth = birth;

}

public String getBegin() {

return begin;

}

public void setBegin(String begin) {

this.begin = begin;

}

public String getEnd() {

return end;

}

public void setEnd(String end) {

this.end = end;

}

public Integer getPage() {

return page;

}

public void setPage(Integer page) {

this.page = page;

}

public Integer getRows() {

return rows;

}

public void setRows(Integer rows) {

this.rows = rows;

}

public Integer getPstart() {

return pstart;

}

public void setPstart(Integer pstart) {

this.pstart = pstart;

}

public Integer getPend() {

return pend;

}

public void setPend(Integer pend) {

this.pend = pend;

}

}

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace就是空间名,它必须在整个项目中都是唯一的 -->

<mapper namespace="com.SSHC.dao.UserinfoDao">

    <!-- id必须是唯一的 -->

    <!-- 创建一个List<Userinfo>集合,变量名叫rmUserinfo -->

    <resultMap type="Userinfo" id="rmUserinfo">

        <!-- userinfo表的主键是id -->

        <!-- property指的是Userinfo类的属性名,

             column指的是userinfo表的列名 -->

        <!-- u.setId(rs.getInt("ID")) -->

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

        <!-- u.setAct(rs.getInt("ACT")) -->

    <result property="act" column="ACT"/>

    <result property="pwd" column="PWD"/>

    <result property="birth" column="BIRTH"/>

    </resultMap>   

    <!-- public List<Userinfo>selectByAct(Userinfo u) -->

    <select id="selectByAct" resultMap="rmUserinfo"

        parameterType="Userinfo">

        select * from userinfo

        <if test="act != null and act.length() > 0">

            where act like #{act}

        </if>

    </select>

    

    <!-- public List<Userinfo> selectByOne(Userinfo u) -->

    <select id="selectByOne" resultMap="rmUserinfo"

        parameterType="Userinfo">

        select * from userinfo where 1 = 1

        <choose>

            <when test="act != null and act.length() > 0">

                and act like #{act}

            </when>

            <when test="birth != null and birth.length() > 0">

                and birth = to_date(#{birth},'yyyy-mm-dd')

            </when>

            <otherwise>

            </otherwise>

        </choose>

    </select>

    

    <!-- public List<Userinfo>selectByCond(Userinfo u) -->

    <select id="selectByCond" resultMap="rmUserinfo"

        parameterType="Userinfo">

        select * from userinfo

        <where>

            <if test="act != null and act.length() > 0">

                and act like #{act}

            </if>

            <if test="pwd != null and pwd.length() > 0">

                and pwd = #{pwd}

            </if>

            <if test="begin != null and begin.length() > 0">

                and birth &gt;= to_date(#{begin},'yyyy-mm-dd')

            </if>

            <if test="end != null and end.length() > 0">

                and birth &lt;= to_date(#{end},'yyyy-mm-dd')

            </if>

        </where>

    </select>

    

    <!-- public List<Userinfo>selectByPage(Userinfo u) -->

    <select id="selectByPage" resultMap="rmUserinfo"

        parameterType="Userinfo">

        select * from

(select t.*,rownum rn from userinfo t

where rownum &lt;= #{pend})

where rn &gt;= #{pstart}

    </select>

</mapper>



/*CTRL+F搜索词条:config:配置

resources:资源

factory:工厂

session“会话控制”,会议,会话

分页查询 */


package Text;

import java.io.IOException;

import java.io.Reader;

import java.util.List;

import java.util.Scanner;


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 com.SSHC.bean.Userinfo;



public class UserinfoSelect {


public static void main(String[] args) {

// TODO Auto-generated method stub

//设置主配置文件的路径path:

String path = "mybatis.xml";

/*

读取mybatis.xml中的配置信息,就是读取四大连接字符串的内容

*/

Reader config;

/*config:配置*/

/*resources:资源*/

/*factory:工厂

* session“会话控制”,会议,会话*/

try {

config = Resources.getResourceAsReader(path);

SqlSessionFactory factory = 

new SqlSessionFactoryBuilder().build(config);

/*数据库的操作对象session(session

* 就是给factory.openSession()起

的别名,我理解的意思是:“工厂开放会话”*/

SqlSession session = factory.openSession();


String exePath = null;



while(true){


System.out.print("请选择操作:1.selectByAct"

+ ",2.selectByOne,"

+ "\n 3.selectByCond,"

+ "4.selectByPage"

+ "\n");

   Scanner input = new Scanner(System.in);

   int num = input.nextInt();

   System.out.println(num);

 


if(num==1){

exePath = "com.SSHC.dao.UserinfoDao.selectByAct";

Userinfo u = new Userinfo();

u.setAct("%诗书画唱%");

List<Userinfo>list = session.selectList(exePath,u);

for(Userinfo user : list) {

System.out.println(user.getId()+" "

+user.getAct()+" "+user.getPwd()+" "

+user.getBirth());

}

}

if(num==2){

exePath = "com.SSHC.dao.UserinfoDao.selectByOne";

Userinfo u = new Userinfo();

u.setAct("%诗书画唱%");

u.setBirth("2020-06-06");

List<Userinfo>list = session.selectList(exePath,u);

for(Userinfo user : list) {

System.out.println(user.getId()+" "

+user.getAct()+" "+user.getPwd()+" "

+user.getBirth());

}

}

if(num==3){

exePath = "com.SSHC.dao.UserinfoDao.selectByCond";

Userinfo u = new Userinfo();

//u.setAct("%诗书画唱%");

//u.setPwd("pwd4");

u.setBegin("2020-06-01");

u.setEnd("2020-06-08");

List<Userinfo>list = session.selectList(exePath,u);

for(Userinfo user : list) {

System.out.println(user.getId()+" "

+user.getAct()+" "+user.getPwd()+" "

+user.getBirth());

}

}

if(num==4){

exePath = "com.SSHC.dao.UserinfoDao.selectByPage";

Userinfo u = new Userinfo();


/*rows=5,page=2

end = rows * page=10

start = (page - 1) * rows + 1=6

start表示>=好后面的值,end表示<=号后面的值*/

/**分页查询 START*/

Integer rows = 5;

Integer page = 2;


Integer start = (page - 1) * rows + 1;

Integer end = page * rows;

u.setPage(page);

u.setRows(rows);

u.setPstart(start);

u.setPend(end);

List<Userinfo>list = session.selectList(exePath,u);

for(Userinfo user : list) {

System.out.println(user.getId()+" "

+user.getAct()+" "+user.getPwd()+" "

+user.getBirth());

}

/**分页查询 END*/

}} } catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}

oracle_drivername=oracle.jdbc.driver.OracleDriver

oracle_url=jdbc:oracle:thin:@localhost:1521:orcl

oracle_username=X

oracle_password=sshcPwd


mysql_drivername=com.mysql.jdbc.Driver

mysql_url=jdbc:mysql://localhost:3306/j190802?useUnicode=true&amp;characterEncoding=GBK2312

mysql_username=root

mysql_password=1


sqlserver_drivername=com.microsoft.sqlserver.jdbc.SQLServerDriver

sqlserver_url=jdbc:sqlserver://localhost:1433;databaseName=cervs

sqlserver_username=sa

sqlserver_password=

log4j.rootLogger=DEBUG,Console

#Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=%d[%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>  

    <!-- 读取指定的properties文件中的内容 -->

    <properties resource="db.properties"></properties> 

    <!-- 给类取一个简短的别名 -->

    <typeAliases>

        <package name="com.SSHC.bean"/>

    </typeAliases>

    <environments default="oracleConf">                 

        <!-- oracle配置 --> 

        <environment id="oracleConf">  

            <transactionManager type="JDBC"> 

                <property name="closeConnection" value="false"/>

            </transactionManager> 

            <!-- 配置数据源 -->       

            <dataSource type="POOLED">

                <property name="driver" value="${oracle_drivername}"/>   

                <property name="url" value="${oracle_url}"/> 

                <property name="username" value="${oracle_username}"/> 

                <property name="password" value="${oracle_password}"/>  

            </dataSource>    

        </environment>

        <!-- mysql配置 -->

        <environment id="mysqlConf">

            <!-- 事务配置 -->

            <transactionManager type="JDBC"> 

                <property name="closeConnection" value="false"/>

            </transactionManager> 

            <!-- 配置数据源 -->       

            <dataSource type="POOLED">

                <property name="driver" value="${mysql_drivername}"/>   

                <property name="url" value="${mysql_url}"/> 

                <property name="username" value="${mysql_username}"/> 

                <property name="password" value="${mysql_password}"/>  

            </dataSource>

        </environment>

    </environments> 

    <!-- 实体映射文件集合 --> 

    <mappers>

        <!-- 告诉mybatis框架,映射文件放在什么地方 -->

        <mapper resource="com/SSHC/bean/UserinfoSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/ProductSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/ProtypeSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/CustomSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/AddrSqlMap.xml"/>

    </mappers>

</configuration>

2.一对多地打印数据,一对一地打印数据


 --drop table custom                

create table custom(

    cid number primary key,

    name varchar2(30) not null,

SEX varchar2(30) not null

);


--drop sequence seq_custom

create sequence seq_custom

start with 1       --起始值是1

increment by 1     --增长的值   

maxvalue 999999999 --序列号的最大值

minvalue 1         --序列号的最小值

nocycle            --是否循环

cache 10;          --预存



insert into custom values(seq_custom.nextval,'A名字','男');

insert into custom values(seq_custom.nextval,'B名字','女');

insert into custom values(seq_custom.nextval,'C名字','男');

insert into custom values(seq_custom.nextval,'D名字','男');

--select * from custom




 --drop table addr                

create table addr(

    aid number primary key,

   text varchar2(30) not null,

cid varchar2(30) not null

);


--drop sequence seq_addr

create sequence seq_addr

start with 1       --起始值是1

increment by 1     --增长的值   

maxvalue 999999999 --序列号的最大值

minvalue 1         --序列号的最小值

nocycle            --是否循环

cache 10;          --预存



insert into addr values(seq_addr.nextval,'江西的收货地址',1);

insert into addr values(seq_addr.nextval,'广东的收货地址',2);

insert into addr values(seq_addr.nextval,'浙江的收货地址',3);

insert into addr values(seq_addr.nextval,'江西的收货地址',1);

insert into addr values(seq_addr.nextval,'广东的收货地址',2);

insert into addr values(seq_addr.nextval,'浙江的收货地址',3);

insert into addr values(seq_addr.nextval,'浙江的收货地址',4);

--select * from addr

package com.SSHC.bean;


public class Addr {

    private Integer aid;

    private String text;

    private Integer cid;

    //关联属性

    private Custom c;

public Integer getAid() {

return aid;

}

public void setAid(Integer aid) {

this.aid = aid;

}

public String getText() {

return text;

}

public void setText(String text) {

this.text = text;

}

public Integer getCid() {

return cid;

}

public void setCid(Integer cid) {

this.cid = cid;

}

public Custom getC() {

return c;

}

public void setC(Custom c) {

this.c = c;

}

}

package com.SSHC.bean;


import java.util.List;


public class Custom {

    private Integer cid;

    private String name;

    private String SEX;

    //关联属性

    private List<Addr>al;

public Integer getCid() {

return cid;

}

public void setCid(Integer cid) {

this.cid = cid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSEX() {

return SEX;

}

public void setSEX(String SEX) {

this.SEX = SEX;

}

public List<Addr> getAl() {

return al;

}

public void setAl(List<Addr> al) {

this.al = al;

}

}

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.SSHC.dao.AddrDao">

    <resultMap type="Addr" id="rmAddr">

        <id property="aid" column="AID" />

    <result property="text" column="TEXT"/>

    <result property="cid" column="CID"/>

    <association property="c" column="CID"

        select="com.SSHC.dao.CustomDao.selectById">

        <id property="cid" column="CID" />

    <result property="name" column="NAME"/>

    <result property="SEX" column="SEX"/>

    </association>

    </resultMap> 

    <!-- public List<Addr>selectByCid(Integer cid) -->

    <select id="selectByCid" resultMap="rmAddr">

        select * from addr where cid = #{cid}

    </select>

    <!-- public List<Addr>selectAll() -->

    <select id="selectAll" resultMap="rmAddr">

        select * from addr

    </select>

</mapper>


<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.SSHC.dao.CustomDao">

    <resultMap type="Custom" id="rmCustom">

        <id property="cid" column="CID" />

    <result property="name" column="NAME"/>

    <result property="SEX" column="SEX"/>

    <collection property="al" javaType="ArrayList" ofType="Addr"

        column="CID" select="com.SSHC.dao.AddrDao.selectByCid">

    </collection>

    </resultMap>    

    <!-- public List<Custom>selectAll() -->

    <select id="selectAll" resultMap="rmCustom">

        select * from custom

    </select>

    <!-- public Custom selectById(Integer cid) -->

    <select id="selectById" resultMap="rmCustom">

        select * from custom where cid = #{cid}

    </select>

</mapper>




package Text;

import java.io.IOException;

import java.io.Reader;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;


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 com.SSHC.bean.Addr;

import com.SSHC.bean.Custom;

import com.SSHC.bean.Product;

import com.SSHC.bean.Protype;

import com.SSHC.bean.Userinfo;



public class YingShe {


public static void main(String[] args) {

// TODO Auto-generated method stub

//设置主配置文件的路径path:

String path = "mybatis.xml";

//读取mybatis.xml中的配置信息,就是读取四大连接字符串的内容

Reader config;

try {

config = Resources.getResourceAsReader(path);

SqlSessionFactory factory = 

new SqlSessionFactoryBuilder().build(config);

//数据库的操作对象session

SqlSession session = factory.openSession();

//调用selectAll

//执行路径就是映射文件的namespace属性+'.'+id

String exePath = null;


while(true){


System.out.print("请选择操作:1.一对多地打印数据"

+ ",2.一对一地打印数据");

   Scanner input = new Scanner(System.in);

   int num = input.nextInt();

   System.out.println(num);

 


if(num==1){


/**下面是一对多地打印出映射(逐组打印出名字和对应

的多个地址),

*/

            exePath = "com.SSHC.dao.CustomDao.selectAll";

            List<Custom>list = session.selectList(exePath);

            for(Custom c : list) {

            System.out.println(c.getName());

            List<Addr>al = c.getAl();

            for(Addr a : al) {

            System.out.println(a.getText());

            }

            System.out.println();

            }

}

/**下面是一对一地打印出映射(逐组打印出地址和对应

  的一个名字)

* 其实也可以一对多地打印出映射,比如上面就是

* 一对多的打印出数据(逐组打印出名字和对应

的多个地址),

* */

if(num==2){

exePath = "com.SSHC.dao.AddrDao.selectAll";

List<Addr>list = session.selectList(exePath);

for(Addr a : list) {

System.out.println(a.getText());

Custom c = a.getC();

if(c != null) {

System.out.println(c.getName());

}

}

// //新增修改和删除一定记得提交事务

// session.commit();

// System.out.println(count);

} }} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}

这3个文件的内容和上面的一样,是共有的内容







包含个人详细注释的例子(几乎无障碍阅读) END



视频教程笔记 START

我对&lt;和&rt;的理解:分别是<>的left左边(<)和right部分(>)。



视频教程笔记 END


单词意思 START


单词意思 END


示例SQL START


create table custom(

    cid number primary key,

    name varchar2(30) not null,

    SEX char(2)

);

insert into custom values(1,'小诗','男');

insert into custom values(4,'小书','女');

insert into custom values(8,'乐画','男');

create table addr(

    aid number primary key,

    text varchar2(50) not null,

    cid number

);

insert into addr values(1,'诗书画唱学院',4);

insert into addr values(2,'诗书画唱创新创业大楼',4);

insert into addr values(3,'五一大道7UP大厦三楼',1);

insert into addr values(4,'书院路冶金大厦一楼',8);

insert into addr values(6,'德雅路48号',8);

insert into addr values(7,'芙蓉广场贸易大厦',8);


select * from addr where cid = 8;

--查询userinfo表,根据act进行模糊查询

--如果没有输入账号,就查询所有

--如果输入了账号,就进行模糊查询


--查询userinfo表,根据act和日期进行查询

--每次查询只使用一个条件,要么根据账号进行查询,

--要么根据日期进行查询,这两个条件是互相排斥的


--组合查询

--act模糊查询

--pwd精确匹配

--brith范围查询


--分页查询

--page当前页码

--rows每页显示记录条数

--end = page * rows【end代表<=后面的数值】

--start = (page - 1) * rows + 1【start代表>=前面的数值】


select * from

(select t.*,rownum rn from userinfo t

where rownum <= end)

where rn >= start








示例SQL END

留给读者的作业(很容易和我提供详细注释的例子相似) START

一、创建商品信息表proinfo,包含id、商品名称和价格两个属性,对proinfo表进行Mybatis配置实现以下的功能:

1、如果输入了价格,就根据价格进行查询,如果没有输入价格,就查询所有。<if>标签实现

2、如果输入了商品名称,就根据商品名称进行模糊查询,否则就查询所有。<if>标签实现

3、同时输入价格和商品名称,优先根据商品名称进行模糊查询,商品名称和价格两个条件只能二选一。<choose><when>标签实现

二、创建宠物信息表,包含id,宠物名字和毛色以及年龄,实现以下功能:

1、如果输入了名字,就根据名字进行查询,如果没有输入名字,就查询所有。

2、如果输入了毛色,就根据毛色进行查询,如果么有输入毛色,就查询所有。

3、同时输入名字、毛色和年龄时,查询条件的优先级别是名字>年龄>毛色,三个条件只能选择一个进行查询。

三、实现一个商品信息表和宠物信息表的分页查询和组合查询功能

留给读者的作业(很容易和我提供详细注释的例子相似) END


Mybatis框架映射,一对多或一对一地打印数据,Oracle动态SQL处理,个人详细注释和单词的评论 (共 条)

分享到微博请遵守国家法律