Java教程

Java入门实战项目之宠物商店 基于mybatis框架

本文主要是介绍Java入门实战项目之宠物商店 基于mybatis框架,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

我发了项目的运行结果视频,感兴趣可以做一做。

老师教了mybatis如何使用,我反复debeg后,基本掌握。

项目比较小,配置文件比较难,奥利给!

1. 导入依赖

 

2. 写MyBatis的配置文件

<?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>
    <settings>
        <!--自动将下划线转换为骆驼命名法-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="develop">
        <!--配置环境-->
        <environment id="develop">
            <!--事务管理为JDBC-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据源 类型是连接池-->
            <dataSource type="POOLED">
                <!--驱动名 5.7或8 是:com.mysql.jdbc.cj.Driver-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--URL-->
                <property name="url" value="jdbc:mysql://localhost:3306/yzx_db?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <!--账号-->
                <property name="username" value="root"/>
                <!--密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置mapper文件的位置-->
    <mappers>
        <mapper resource="mapper/PetMapper.xml"></mapper>
    </mappers>
</configuration>

3. 写Mapper接口

package com.hope.day8.mapper;

import com.hope.day8.entity.Pet;

import java.util.ArrayList;

public interface PetMapper {
    ArrayList<Pet> showPets();           //查看所有的宠物
    Pet findPetByName(String name);//通过名字查看所有的宝物
    void inputPet(Pet pet);//输入宠物信息,录入系统中
    int updatePet(Pet pet);//修改系统中的宠物信息
    void removePet(String name);//删除宠物的信息
    ArrayList<Pet> sortPetsByAge();//按年龄进行排序
    ArrayList<Pet> sortPetsByPrice();// 按价格进行排序
}

4. 写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">
<!--namespace命名空间配置接口路径-->
<mapper namespace="com.hope.day8.mapper.PetMapper">
    <!--insert是添加操作 id是方法名 parameterType是参数类型 #{stuName}是获得参数对象中的属性值-->
    <insert id="inputPet" parameterType="com.hope.day8.entity.Pet">
    insert into pets(id,name,sex,type,age,price,weight) values (#{id},#{name},#{sex},#{type},#{age},#{price},#{weight});
    </insert>


    <select id="findPetByName" resultType="com.hope.day8.entity.Pet">
        select * from pets where name=#{name}
    </select>

    <update id="updatePet" parameterType="com.hope.day8.entity.Pet">
        update pets set id=#{id},name=#{name},sex=#{sex},type=#{type},age=#{age},price=#{price},weight=#{weight}
        where id=#{id};
      </update>

    <!--resultType是查询的返回类型-->
    <select id="showPets"  resultType="com.hope.day8.entity.Pet">
        select * from pets
    </select>

    <delete id="removePet" parameterType="java.lang.String" >
        delete  from pets where name=#{name} ;
    </delete>

    <select id="sortPetsByAge" resultType="com.hope.day8.entity.Pet">
        SELECT * FROM pets order by age desc;
    </select>

    <select id="sortPetsByPrice" resultType="com.hope.day8.entity.Pet">
        SELECT * FROM pets order by price desc;
    </select>


</mapper>

5. 调用Mapper接口

package com.hope.day8;
import com.hope.day8.entity.Pet;
import com.hope.day8.mapper.PetMapper;
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.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class MyBatisDemo {
    public static void main(String[] args) {
        //创建会话工厂创建器,用于读取配置文件
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //读取配置文件,获得工厂
        try {
            //如果程序运行失败,执行catch语句
            while (true) {
                //使得程序一直运行
            SqlSessionFactory factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
            //获得会话
            SqlSession sqlSession = factory.openSession();
            //获得Mapper对象
            PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
            //调用方法
                System.out.println("------------------------欢迎进入宠物管理系统---------------------------");
                System.out.println(
                        "1.查看宠物 2.按名查找宠物 3.增加宠物 4.修改宠物 5.删除宠物 6.按年龄排序 7.按价格排序"
                );
                Scanner scanner = new Scanner(System.in);
                System.out.println("请进行选择:");
                int op = scanner.nextInt();
                switch (op) {
                    case 1:
                        ArrayList<Pet> arrayList = petMapper.showPets();
                        for (int i = 0; i < arrayList.size(); i++) {
                            System.out.println(arrayList.get(i));
                        }
                        System.out.println("这是所有的宠物");
                        break;
                    case 2:
                        System.out.println("要查找的宠物名字是:");
                        Pet pet = petMapper.findPetByName(scanner.next());
                        //创建对象获得返回值
                        System.out.println(pet);
                        break;
                    case 3:
                        //增加宠物
                        Pet A = new Pet();//创建对象保存宠物信息
                        System.out.println("要添加的宠物id是:");
                        A.setId(scanner.nextInt());
                        System.out.println("要添加的宠物名字是:");
                        A.setName(scanner.next());
                        System.out.println("要添加的宠物性别是:");
                        A.setType(scanner.next());
                        System.out.println("要添加的宠物种类是:");
                        A.setSex(scanner.next());
                        System.out.println("要添加的宠物年龄是:");
                        A.setAge(scanner.nextInt());
                        System.out.println("要添加的宠物价格是:");
                        A.setPrice(scanner.nextInt());
                        System.out.println("要添加的宠物重量是:");
                        A.setWeight(scanner.nextInt());
                        petMapper.inputPet(A);//A作为参数,调用方法
                        System.out.println("宠物已添加!");
                        break;
                    case 4:
                        //修改宠物信息
                        Pet B = new Pet();
                        System.out.println("要修改的宠物id是:");
                        B.setId(scanner.nextInt());
                        System.out.println("宠物名字是");
                        B.setName(scanner.next());
                        System.out.println("宠物性别是:");
                        B.setSex(scanner.next());
                        System.out.println("宠物种类是:");
                        B.setType(scanner.next());
                        System.out.println("宠物年龄是:");
                        B.setAge(scanner.nextInt());
                        System.out.println("宠物价格是:");
                        B.setPrice(scanner.nextInt());
                        System.out.println("宠物重量是:");
                        B.setWeight(scanner.nextInt());
                        petMapper.updatePet(B);
                        System.out.println("修改成功");
                        break;
                    case 5:
                        System.out.println("要删除的宠物名字是:");
                        petMapper.removePet(scanner.next());
                        System.out.println("删除成功!");
                        break;
                    case 6:
                        ArrayList<Pet> arrayList1 = petMapper.sortPetsByAge();
                        //通过数组保存返回值
                        for (int i = 0; i < arrayList1.size(); i++) {
                            System.out.println(arrayList1.get(i));
                        }
                        System.out.println("按年龄排序!");
                        break;
                    case 7:
                        ArrayList<Pet> arrayList2 = petMapper.sortPetsByPrice();
                        for (int i = 0; i < arrayList2.size(); i++) {
                            System.out.println(arrayList2.get(i));
                        }
                        System.out.println("按价格排序!");
                        break;
                    default:
                        return;//出错就返回
                }
                //提交,关闭
                sqlSession.commit();
                sqlSession.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("系统有非法入侵!");
        }
       }

}

这篇关于Java入门实战项目之宠物商店 基于mybatis框架的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!