Maven的环境搭建和Mybatis注解、xml文件的使用

Maven的环境搭建和Mybatis注解、xml文件的使用,第1张

Maven
概念:管理和构建java项目的工具
作用
1、统一了java项目目录结构
2、提供了一套标准化的项目构建流程(清理、编译、测试、打包、安装…)
3、依赖管理(管理jar)
配置
1、maven环境变量配置
1、MAVEN_HOME,值为maven的根目录
2、在path中配置:%MAVEN_HOME%\bin
2、在conf/settings.xml中配置【配置一次】
1、配置本地仓库,每个人的仓库路径不一样。
D:\develop\maven_repository
2、在mirrors标签中配置aliyu中央仓库镜像

alimaven
aliyun maven
http://maven.aliyun.com/nexus/content/groups/public/
central

3、全局的jdk1.8,解决了"不支持的发行版本xx",自己去md笔记中复制

3、idea集成maven【配置两遍】

Mybatis
概念和作用:是一个持久层框架,简化了jdbc开发。

mybatis快速入门【搭建mybatis环境】

2.1【第一大步】环境搭建
  • 创建user表,添加数据

    create database mybatis;
    use mybatis;
    
    drop table if exists tb_user;
    
    create table tb_user(
    	id int primary key auto_increment,
    	username varchar(20),
    	password varchar(20),
    	gender char(1),
    	addr varchar(30)
    );
    
    INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
    INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
    INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');
    
  • 创建模块day04-mybatis,在创建好的模块中的 pom.xml 配置文件中添加依赖的坐标

    	<dependencies>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
    
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.46version>
        dependency>
    
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
            <scope>testscope>
        dependency>
    dependencies>
    
  • 创建包结构,在 com.itheima.pojo 包下创建和表对应的 User类

public class User {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;
    
    //省略了 setter 和 getter
}
2.2【第二大步】编写核心配置文件

在resources中编写mybatis-config.xml配置文件,配置数据库的连接信息,在mybatis官网复制即可。


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>

    
    
configuration>
2.3【第三大步】编写mapper接口和SQL语句

增:

//单元测试类中
InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
        SqlSession sqlSession = factory.openSession(true);
        Usermapper mapper = sqlSession.getMapper(Usermapper.class);
        User user = new User();
        user.setUsername("胡歌");
        user.setPassword("1314");
        user.setGender("男");
        user.setAddr("武汉");
        mapper.insert(user);
        sqlSession.close();
//mapper接口中
@Insert("insert into tb_user values(null,#{username},#{password},#{gender},#{addr} )")
    void insert(User user);

删:

//单元测试类中
 public void delete() throws IOException {
        InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
        SqlSession sqlSession = factory.openSession(true);
        Usermapper mapper = sqlSession.getMapper(Usermapper.class);
        mapper.delete(2);
        sqlSession.close();
    }
//mapper接口中
   @Delete("delete from tb_user where id=2")
    void delete(int id);

改:

//mapper接口中
  @Update("update  tb_user set username=#{username},password=#{password},gender=#{gender},addr=#{addr} where id=#{id} ")
    void updatess(User user);
//单元测试类中	
 public void updateq() throws IOException {
        InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
        SqlSession sqlSession = factory.openSession(true);
        Usermapper mapper = sqlSession.getMapper(Usermapper.class);
        User user = new User();
        user.setId(3);
        user.setUsername("胡歌");
        user.setPassword("1314");
        user.setGender("男");
        user.setAddr("武汉");
        mapper.insert(user);
        mapper.updatess(user);
        sqlSession.close();
    }

查:

//mapper接口中
 @Select("select * from tb_user")
    List<User> selectall();

//单元测试类中

 public void selectAll() throws IOException {
    InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
    SqlSession sqlSession = factory.openSession();
    Usermapper mapper = sqlSession.getMapper(Usermapper.class);
    List<User> list = mapper.selectall();
    list.forEach(user -> System.out.println(user));
sqlSession.close();
}

xml文件方式配置SQL

准备工作
先再java这个包下创建两个包,mapper和pojo

再在mapper这个包下创建一个接口类UserMapper,

public interface UserMapper {

    List<User> selectaller();

    void  delete(int id);

    void insert (User user);

    void update (User user);
}

再pojo这个包下,创建一个封装类,用来封装数据

public class User {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;
    //省略set和get没写
    

在resources包下,创建mybatis.config.xml文件,用来连接数据库以及获取sql语句


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        
        <package name="com.itheima.mapper"/>
    mappers>

    
    
configuration>

在reaources包下创建一个UserMapper.xml 用来写sql语句,


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">







<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectaller" resultType="com.itheima.pojo.User">
            select *
            from tb_user;
        select>

    <delete id="delete">
        delete from tb_user where id=#{id};
    delete>

<insert id="insert">
    insert into tb_user
    values (null,#{username},#{password},#{gender},#{addr})
insert>

    <update id="update">
        update tb_user set username=#{username},password=#{password},gender=#{gender},addr=#{addr} where id=#{id}
    update>

mapper>

必须跟mapper下的接口,是同名
如下

在test报下创建一个测试类,用来测试java代码

1,通过xml文件实现增加用户信息
UserMapper接口中

public interface UserMapper {

    void insert (User user);

xml文件中

<insert id="insert">
    insert into tb_user
    values (null,#{username},#{password},#{gender},#{addr})
insert>

测试类中

 @Test
    public void inserter() throws IOException {
        InputStream stream = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(stream).openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        //user.setId();
        user.setUsername("李逍遥");
        user.setPassword("123456");
        user.setGender("男");
        user.setAddr("武汉");
        mapper.insert(user);
        sqlSession.close();
    }

2,通过xml文件实现删除用户信息
UserMapper接口中

public interface UserMapper {

    void  delete(int id);

xml文件中

  <delete id="delete">
        delete from tb_user where id=#{id};
    delete>

测试类中

  @Test
    public void delete() throws IOException {
        InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       mapper.delete(11);
        sqlSession.close();
    }

3,通过xml文件实现修改用户信息
UserMapper接口中

public interface UserMapper {
    
    void update (User user);

xml文件中

<update id="update">
        update tb_user set username=#{username},password=#{password},gender=#{gender},addr=#{addr} where id=#{id}
    update>

测试类中

@Test
    public  void  updateset() throws IOException {
        InputStream stream = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(stream).openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(3);
        user.setUsername("爱你");
        user.setPassword("1314");
        user.setAddr("大武汉");
        user.setGender("男");
        mapper.update(user);
        sqlSession.close();
    }

4,通过xml文件实现查询用户信息
UserMapper接口中

public interface UserMapper {
    
    List<User> selectaller();

xml文件中

<select id="selectaller" resultType="com.itheima.pojo.User">
            select *
            from tb_user;
        select>

测试类中

@Test
    public void select() throws IOException {
        InputStream rs = Resources.getResourceAsStream("mybatis.config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(rs);
        SqlSession sqlSession = factory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> list = mapper.selectaller();
        list.forEach(user -> System.out.println(user));
        sqlSession.close();
    }
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/735812.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存