✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。
文章目录
- 案例
- 建表
- 配置
- Animal类
- DBUtils数据库工具类
- DateUtils日期类
- AnimalDaoImpl类
- AnimalServiceImpl类
- AnimalTest测试类
案例
使用读取配置文件的形式连接数据库,(Dao层+service层)对animal表进行增删改查操作。
animal表字段如下
aid int 主键 自增长 -->宠物编号
name varchar(10) 非空 -->宠物名称
age int 非空 -->宠物年龄
birthday Date 非空
建表
CREATE TABLE IF NOT EXISTS `animal`(
`aid` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(10) NOT NULL,
`age` INT NOT NULL,
`birthday` DATE
);
配置
添加mysql-connector-java-5.1.0-bin.jar文件并使用。
添加db.properties文件
Animal类
定义一个Animal类,添加和animal表字段相同的私有变量
// 定义属性
private int aid;
private String name;
private int age;
private Date birthday;
添加一个无参构造
public Animal() {
super();
}
添加一个全部字段的有参构造
public Animal(int aid, String name, int age, Date birthday) {
super();
this.aid = aid;
this.name = name;
this.age = age;
this.birthday = birthday;
}
添加一个不带aid字段的有参构造
public Animal(String name, int age, String gender, Date birthday,
String identityCard, String phone, String address, double salary) {
super();
this.name = name;
this.age = age;
this.birthday = birthday;
}
给私有变量添加get/set方法
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
重写ToString方法
@Override
public String toString() {
return "Animal [aid=" + aid + ", name=" + name + ", age=" + age
+ ", birthday=" + birthday + "]";
}
DBUtils数据库工具类
声明一个ThreadLocal对象,用来存储Connection连接对象;注册驱动、获取连接、然后释放资源方法。
private static final Properties PROPERTIES = new Properties();
// 声明一个ThreadLocal<Connection>对象,用来存储Connection连接对象
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
static {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);
// 1、注册驱动
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 2、获取连接方法
public static Connection getConnection() {
Connection connection = threadLocal.get();
// 2、获取连接对象
try {
// 如果连接对象为null,创建一个连接对象
if (connection == null) {
connection = DriverManager.getConnection(
PROPERTIES.getProperty("url"),
PROPERTIES.getProperty("username"),
PROPERTIES.getProperty("password"));
threadLocal.set(connection);
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
// 3、释放资源方法
public static void closeAll(ResultSet resultSet, Statement statement,
Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
// 移除 ThreadLocal<Connection> 对象
threadLocal.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
开启事务
public static void startTransaction() {
Connection connection = getConnection();
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
提交事务
public static void commitTransaction() {
Connection connection = getConnection();
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, null, connection);
}
}
回滚事务
public static void rollbackTransaction() {
Connection connection = getConnection();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, null, connection);
}
}
DateUtils日期类
public class DateUtils {
// 声明一个SimpleDateFormat类型的静态常量
public static final SimpleDateFormat SIMPLEDATEFORMAT=new SimpleDateFormat("yyyy-MM-dd");
// 定义方法实现将字符串类型的数据转换成java.util.Date类型
public static java.util.Date strToUtilDate(String strDate){
try {
return SIMPLEDATEFORMAT.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
// 定义方法实现将java.util.Date类型转换为字符串
public static String utilDateToString(java.util.Date utilDate){
return SIMPLEDATEFORMAT.format(utilDate);
}
// 定义方法实现架构java.util.Date类型转换为java.sql.Date类型
public static java.sql.Date utilDateToSqlDate(java.util.Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
}
AnimalDaoImpl类
DAO层叫数据访问层,全称为data access object,属于一种比较底层,比较基础的操作,具体到对于某个表的增删改查,也就是说某个DAO一定是和数据库的某一张表一一对应的,其中封装了增删改查基本操作,建议DAO只做原子操作,增删改查。
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AnimalDaoImpl {
//全局变量
PreparedStatement preS=null;
Connection connection;
//增
public int insert(Animal animal){
//获取链接
connection=DBUtils.getConnection();
String sql="insert into animal values(?,?,?,?);";
try {
preS=connection.prepareStatement(sql);
// 绑定参数
preS.setInt(1, animal.getAid());
preS.setString(2, animal.getName());
preS.setInt(3, animal.getAge());
preS.setDate(4, DateUtils.utilDateToSqlDate(animal.getBirthday()));
return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.closeAll(null, preS, null);
}
return 0;
}
//删
public int delete(int aid) {
//获取链接
connection = DBUtils.getConnection();
String sql = "delete from animal where aid = ?;";
try {
preS = connection.prepareStatement(sql);
// 绑定参数
preS.setInt(1, aid);
return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, preS, null);
}
return 0;
}
//改
public int update(Animal animal) {
//获取链接
connection = DBUtils.getConnection();
String sql = "update animal set name = ?,age = ?,birthday= ? where aid=?;";
try {
preS = connection.prepareStatement(sql);
// 绑定参数
preS.setString(1, animal.getName());
preS.setInt(2, animal.getAge());
preS.setDate(3, DateUtils.utilDateToSqlDate(animal.getBirthday()));
preS.setInt(4, animal.getAid());
return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, preS, null);
}
return 0;
}
//查(单个)
public Animal select(int aid) {
ResultSet resultSet = null;
Animal animal = null;
//获取连接
connection = DBUtils.getConnection();
String sql = "select * from animal where aid = ?";
try {
preS = connection.prepareStatement(sql);
// 绑定参数
preS.setInt(1, aid);
resultSet = preS.executeQuery();
if (resultSet.next()) {
animal=new Animal(aid, resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4));
}
return animal;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(resultSet, preS, null);
}
return null;
}
//查(全部)
public List<Animal> selectAll() {
ResultSet resultSet = null;
Animal animal = null;
List<Animal> animalList = new ArrayList<Animal>();
//获取连接
connection = DBUtils.getConnection();
String sql = "select * from animal";
try {
preS = connection.prepareStatement(sql);
resultSet = preS.executeQuery();
while (resultSet.next()) {
animal=new Animal(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4));
animalList.add(animal);
}
return animalList;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(resultSet, preS, null);
}
return null;
}
}
AnimalServiceImpl类
Service层叫服务层,被称为服务,粗略的理解就是对一个或多个DAO进行的再次封装,封装成一个服务,所以这里也就不会是一个原子操作了,需要事物控制。
public class AnimalServiceImpl {
//定义AnimalDaoImpl对象
AnimalDaoImpl animalDao=new AnimalDaoImpl();
//新增信息
public boolean addNewData(Animal animal) {
int num=animalDao.insert(animal);
if(num!=0){
return true;
}else{
return false;
}
}
//删除信息
public boolean delDate(int aid){
int num=animalDao.delete(aid);
if(num!=0){
return true;
}else{
return false;
}
}
//修改信息
public boolean updateDate(Animal animal){
int num=animalDao.update(animal);
if(num!=0){
return true;
}else{
return false;
}
}
//查询信息
public boolean selectDate(int aid){
Animal animal=animalDao.select(aid);
if(animal!=null){
return true;
}else{
return false;
}
}
//查询所有信息
public void selectAllDates(){
List<Animal> animalList=animalDao.selectAll();
if(animalList.size()>0){
System.out.println("****所有动物信息****");
for (Animal animal : animalList) {
System.out.println(animal);
}
}
}
}
AnimalTest测试类
package cn.bdqn.demo02;
public class AnimalTest {
public static void main(String[] args) {
//创建AnimalServiceImpl对象
AnimalServiceImpl animalServiceImpl = new AnimalServiceImpl();
//增加三条数据
Animal animal1 = new Animal(1, "旺财", 3,DateUtils.strToUtilDate("2019-08-18"));
Animal animal2 = new Animal(2, "tom", 4,DateUtils.strToUtilDate("2018-06-25"));
Animal animal3 = new Animal(3, "佩奇", 5,DateUtils.strToUtilDate("2017-07-02"));
animalServiceImpl.addNewData(animal1);
animalServiceImpl.addNewData(animal2);
animalServiceImpl.addNewData(animal3);
//删(aid=3)的数据
animalServiceImpl.delDate(3);
//改
Animal animal4 = new Animal(1, "旺财", 4,DateUtils.strToUtilDate("2018-12-18"));
animalServiceImpl.updateDate(animal4);
//查一条(aid=2)的数据
animalServiceImpl.selectDate(2);
//查全部
animalServiceImpl.selectAllDates();
}
}