Eclipse+Maven+mybaits简单实例

文章目录

  • 一、数据库
  • 二、eclipse maven建立Java Web项目
  • 三、Web Demo
    • 1、实体类
    • 2、DAO接口和DAOImp实现类
    • 3、逻辑层
    • 4、控制器
    • 四、mybaits Demo
    • 1、pom.xml
    • 2、mybaits.xml
    • 3、flowerDaoImp.xml
    • 4、测试showAll 方法

一、数据库

CREATE TABLE `flower`  (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT 'id表示',
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '花卉名称',
  `price` decimal(20, 2) NOT NULL COMMENT '花卉价格',
  `address` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '产地',
  PRIMARY KEY (`id`) USING BTREE
) 

-- ----------------------------
-- Records of flower
-- ----------------------------
INSERT INTO `flower` VALUES (1, '牵牛花', 2.50, '合肥');
INSERT INTO `flower` VALUES (4, '玫瑰', 4.50, '兰州');
INSERT INTO `flower` VALUES (5, '牡丹', 2.50, '洛阳');
INSERT INTO `flower` VALUES (14, '测试星系', 12.00, '沈阳');
INSERT INTO `flower` VALUES (15, '罗', 12.00, '沈阳');
INSERT INTO `flower` VALUES (16, '个人', 22.00, '个人不同');

二、eclipse maven建立Java Web项目

1、File->new ->other->Maven Project
Eclipse+Maven+mybaits简单实例_第1张图片
2、记得选择Create a simple project
Eclipse+Maven+mybaits简单实例_第2张图片
3、
Eclipse+Maven+mybaits简单实例_第3张图片
4、最终产生目录结构
Eclipse+Maven+mybaits简单实例_第4张图片

/src/main/java/ java源码
/src/main/resource java各种配置文件,资源文件
/src/main/webapp web各种源文件,格式文件如css,js,html,jsp等
/src/test/java java测试代码
/target 文件编译过程中生成的.class文件,jar,war等
pom.xml 主要是进行依赖的配置,配置修改后需要maven update

在编写Java源码的时候在Java Resource包下新建不同种类的包

三、Web Demo

自己刚开始接触Mybaits框架,目前主流的框架式SSM,其实各种框架相当于提前给程序员一个轮廓,程序员只需要往里边填空。在一个完整的项目中,从底层到上层之间的所涉及的内容:
1、DB数据库:用来粗女户数据
2、数据访问层(持久化层DAO):主要是对DB进行增删改查的操作
3、逻辑层:Service主要进行逻辑控制,封装了DAO中的内容
4、控制层:Servlet 用来与前端交互,根据前端不同的url地址来给出不同的response
#5、实体类:也就是模型层pojo(简单Java数据类型),主要就是对数据库中的实体封装

整个项目目录结构;
Eclipse+Maven+mybaits简单实例_第5张图片

1、实体类

数据表实体类:flower

在这里插入图片描述

package com.robin.Flower;

public class Flower {

	private int id;
	private String name;
	private double price;
	private String address;

	public Flower() {
		// TODO Auto-generated constructor stub
	}

	public Flower(int id, String name, double price, String address) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.address = address;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Flower [id=" + id + ", name=" + name + ", price=" + price + ", address=" + address + "]";
	}

}

2、DAO接口和DAOImp实现类

mybaits后期会代替该实现类

Eclipse+Maven+mybaits简单实例_第6张图片
LoggableStatement类主要是用来打印出Prestatement拼接后的SQL语句
FlowerDAO类:

package com.robin.DAO;

import java.util.List;

import com.robin.Flower.Flower;

/**
 * 	数据访问层
 * @author 12803
 *
 */
public interface FlowerDao {

	public List<Flower> showAll();//查询全部
	public int insert(Flower flower);//插入元素
}

DAOImp类:

package com.robin.DaoImp;

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 com.robin.DAO.FlowerDao;
import com.robin.Flower.Flower;

public class FlowerDaoImp implements FlowerDao {
	static final String Driver_name = "com.mysql.jdbc.Driver";
	static final String Driver_url ="jdbc:mysql://localhost:3306/robin_test";
	@Override
	public List<Flower> showAll() {
		List<Flower> list = new ArrayList<Flower>();
		Connection conn = null;
		PreparedStatement pre = null;
		// 连接数据库
		try {
			Class.forName(Driver_name);
			System.out.println("连接数据库...");
			conn = DriverManager.getConnection(Driver_url, "root", "123456");
			String sql = "select * from flower";
			pre = conn.prepareStatement(sql);
			ResultSet res = pre.executeQuery();
			while (res.next()) {
				int flower_id = res.getInt(1);
				list.add(new Flower(flower_id, res.getString(2), res.getFloat(3), res.getString(4)));
			}
			res.close();
			pre.close();
			conn.close();

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

		}
		return list;
	}

	@Override
	public int insert(Flower flower) {
		Connection conn = null;
		PreparedStatement pre = null;
		int res = 0;
		// 连接数据库
		try {
			Class.forName(Driver_name);
			conn = DriverManager.getConnection(Driver_url, "root", "123456");
			String sql = "insert into flower values(0,?,?,?);";
			pre = new LoggableStatement(conn, sql);
			pre.setString(1, flower.getName());
			pre.setDouble(2, flower.getPrice());
			pre.setString(3, flower.getAddress());
			System.out.println("Execute sql:"+((LoggableStatement)pre).getQueryString());//输出即将执行的语句
			res = pre.executeUpdate();
			pre.close();
			conn.close();

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
		}
		return res;
	}

LoggableStatement类:
代码是该博客里边的:https://blog.csdn.net/A_Bear/article/details/82192921

3、逻辑层

在这里插入图片描述
FlowerService接口:


import java.util.ArrayList;
import java.util.List;

import com.robin.Flower.Flower;

/**
 * 	逻辑层
 * @author 12803
 *
 */
public interface FlowerService  {
	List<Flower> list = new ArrayList<Flower>();
	public List<Flower> show();
	public int insert(Flower flower);
}

serviceImp类:

import java.util.List;

import com.robin.DAO.FlowerDao;
import com.robin.DaoImp.FlowerDaoImp;
import com.robin.Flower.Flower;
import com.robin.Service.FlowerService;

public class FlowerServiceImp implements FlowerService {
	private FlowerDao flower = new FlowerDaoImp();
	@Override
	public List<Flower> show() {
		//System.out.println("逻辑层");
		return flower.showAll();
	}
	@Override
	public int insert(Flower f) {
		int index = flower.insert(f);
		return index;
	}

}

4、控制器

主要是与前端交互,根据不同的url地址或者请求来调用不同的控制器

在这里插入图片描述
showServlet类主要用来展示花卉:

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.robin.Flower.Flower;
import com.robin.FlowerServiceImp.FlowerServiceImp;
import com.robin.Service.FlowerService;

@WebServlet("/show")
public class ShowServlet extends HttpServlet {
	private FlowerService flowerservice = new FlowerServiceImp();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Flower> list = flowerservice.show();
		req.setAttribute("list", list);
		req.getRequestDispatcher("index.jsp").forward(req, resp);//请求转发
	}
}

index.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@  taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<style type="text/css">
a {
	color: black;
}
a:hover {
	color: red;
}
</style>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tr>
			<th>花卉编号</th>
			<th>花卉名称</th>
			<th>花卉价格</th>
			<th>花卉产地</th>
		</tr>
		<c:forEach items="${list}" var="flower">
			<tr>
				<td>${flower.id}</td>
				<td>${flower.name}</td>
				<td>${flower.price}</td>
				<td>${flower.address}</td>
			</tr>
		</c:forEach>
	</table>
	<a href="insert.jsp">添加花卉信息</a>
</body>
</html>

展现效果:
Eclipse+Maven+mybaits简单实例_第7张图片
addServlet控制器主要用来添加花卉:

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.robin.Flower.Flower;
import com.robin.FlowerServiceImp.FlowerServiceImp;
import com.robin.Service.FlowerService;

@WebServlet("/insert")
public class AddServlet extends HttpServlet {
	private FlowerService flowerservice = new FlowerServiceImp();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String address = req.getParameter("address");
		System.out.println(name);
		Flower flower  = new Flower();
		flower.setName(name);
		flower.setAddress(address);
		flower.setPrice(Double.parseDouble(price));
		int index = flowerservice.insert(flower);
		if(index>0) {
			//重定向是为了防止表单重复提交
			resp.sendRedirect("/mybaits2/show");
		}else {
		}
	}
}

insert.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

<body>
	<form action="insert" method="post">
		<table>
			<tr colspan="2">新增花卉信息</tr>
			<tr>
				<td>花卉名称:</td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<td>花卉价格:</td>
				<td><input type="text" name="price"></td>
			</tr>
			<tr>
				<td>花卉产地:</td>
				<td><input type="text" name="address"></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="提交"> <input
					type="reset" value="重置"></td>
			</tr>
		</table>
	</form>
</body>
</html>

效果:
Eclipse+Maven+mybaits简单实例_第8张图片

四、mybaits Demo

首先mybaits 主要是用来代替数据访问层,也就是变相实现FlowDaoImp的功能,既然替代该功能必须要去给出(1)全局配置,主要是用来连接数据库(2)具体DaoImp实现类

1、pom.xml

最近越来越喜欢maven,将jar包的管理交给maven,只需要给出具体的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.robin</groupId>
	<artifactId>mybaits2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<!-- 确定项目的编译版本 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<!-- servlet 基础 -->
		<!-- jsp and servlet start -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<!--jsp and servlet end -->
		<!-- jstl标签库 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- mysql连接驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.26</version>
		</dependency>
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- Mybaits -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>

		<!-- 补全项目依赖 -->

		<!-- 1:日志 slf4j是规范/接口 日志实现:log4j,logback,common-logging 
		这里使用:slf4j + log4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
	</dependencies>

</project>

2、mybaits.xml

<?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>
	<environments default="mysql">
		<environment id="mysql">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/robin_test" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="flowerDaoImp.xml"/>
	</mappers>
</configuration>

3、flowerDaoImp.xml

<?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 包名.类名 (表示DAO的实现类,名字随便起) -->
<mapper namespace="com.robin.Virtual.FlowerDaoImp">
	<!-- 通过resultMap解决实体类属性与数据库字段名不一致的问题 -->
	<resultMap type="com.robin.Flower.Flower" id="flowerResult">
		<id property="id" column="id" />
		<result property="name" column="name" />
		<result property="price" column="price" />
		<result property="address" column="address" />
	</resultMap>
	<!-- 插入 -->
	<insert id="insert" keyProperty="id" keyColumn="id">
		insert into flower
			(name,price,address)
		values
			(#{name},#{price},#{address})
	</insert>
	<!-- 更新 -->
	<update id="update">
		update flower
		set
			name = #{name}
			price = #{price}
			address = #{address}
		where
			id=#{id}
	</update>
	<!-- 删除 -->
	<delete id="delete">
		delete from flower where id=#{id}
	</delete>
	<!-- 查询所有用户 -->
	<select id="showAll" resultMap="flowerResult">
		select * from flower
	</select>
	<!-- 查询具体某一个用户 -->
	<select id="findbyId" resultMap="flowerResult">
		select * from flower where
		id=#{id}
	</select>

</mapper>

4、测试showAll 方法

因为没有整合该框架,因此选择编写测试类


```java
package com.robin.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

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 org.slf4j.LoggerFactory;

import com.robin.Flower.Flower;

public class testMethod {
	public static void main(String[] args) throws IOException {
		InputStream in = Resources.getResourceAsStream("mybaits.xml");//输入流
		//主要是通过build设计模式建立工厂
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//生产Session
		SqlSession session =  factory.openSession();
		List<Flower> list = session.selectList("com.robin.Virtual.FlowerDaoImp.showAll");
		for (Flower flower : list) {
			System.out.println(flower.toString());
		}
	}
	

}

效果图:
Eclipse+Maven+mybaits简单实例_第9张图片

你可能感兴趣的:(Mybaits)