Java + myBatis + MySql

本文详细介绍了如何使用MyBatis框架从Java应用连接MySQL数据库,并通过XML配置和Mapper文件进行操作。涵盖了数据库配置、类定义、DAO实现及连接池的创建,演示了基本的CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Connecting to MySQL from Java application using myBatis.

Objective

  • How to connect to MySQL database from Java application using myBatis?
  • How to use MyBatis config & mapper using XML?

Environment

Eclipse (Indigo)

Libraries

-mySql java connector (jar)
- myBatis 3.1.1

( 1 ) Database

这里写图片描述
这里写图片描述

( 2 ) Java Project

  • Create new Java Project
  • Add new folder “lib”
  • Copy mysql-connector-java (jar) and myBatis to “lib” folder
  • Add jars file to java build path

( 3 ) Java Classes

Person.java
PersonDAO.java
MyBatisConnectionFactory.java
Main.java

Person.java

package com.hmkcode.vo;

public class Person  {

    private int id;
    private String name;
    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 String toString(){
        return "id: "+id+" Name: "+name;
    }

}

PersonDAO.java

package com.hmkcode.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.hmkcode.vo.Person;

public class PersonDAO {

    private SqlSessionFactory sqlSessionFactory = null;

    public PersonDAO(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory = sqlSessionFactory;
    }

    /**
     * Returns the list of all Person instances from the database.
     * @return the list of all Person instances from the database.
     */
    @SuppressWarnings("unchecked")
    public  List<Person> selectAll(){
        List<Person> list = null;
        SqlSession session = sqlSessionFactory.openSession();

        try {
            list = session.selectList("Person.selectAll");
        } finally {
            session.close();
        }
        System.out.println("selectAll() --> "+list);
        return list;

    }
    /**
     * Select instance of Person from the database.
     * @param person the instance to be persisted.
     */
   public Person selectById(int id){
        Person person = null;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            person = session.selectOne("Person.selectById", id);

        } finally {
            session.close();
        }
        System.out.println("selectById("+id+") --> "+person);
        return person;
    } 
    /**
     * Insert an instance of Person into the database.
     * @param person the instance to be persisted.
     */
   public int insert(Person person){
       int id = -1;
        SqlSession session = sqlSessionFactory.openSession();

        try {
            id = session.insert("Person.insert", person);
        } finally {
            session.commit();
            session.close();
        }
        System.out.println("insert("+person+") --> "+person.getId());
        return id;
    }
    /**
   * Update an instance of Person into the database.
   * @param person the instance to be persisted.
   */
    public void update(Person person){
       int id = -1;
      SqlSession session = sqlSessionFactory.openSession();

      try {
          id = session.update("Person.update", person);

      } finally {
          session.commit();
          session.close();
      }
      System.out.println("update("+person+") --> updated");
  }

    /**
     * Delete an instance of Person from the database.
     * @param id value of the instance to be deleted.
     */
    public void delete(int id){

        SqlSession session = sqlSessionFactory.openSession();

        try {
            session.delete("Person.delete", id);
        } finally {
            session.commit();
            session.close();
        }
        System.out.println("delete("+id+")");

    }
}

MyBatisConnectionFactory.java

package com.hmkcode.mybatis;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisConnectionFactory {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {

            String resource = "com/hmkcode/mybatis/config.xml";
            Reader reader = Resources.getResourceAsReader(resource);

            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            }
        }
        catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        catch (IOException iOException) {
            iOException.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

Main.java

package com.hmkcode;

import java.util.List;

import com.hmkcode.mybatis.MyBatisConnectionFactory;
import com.hmkcode.dao.PersonDAO;
import com.hmkcode.vo.Person;

public class Main {

    public static void main(String args[]){

        // Laod spring-config.xml file
        //ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/config/spring-config.xml");

        //get jdbcTemplatePersonDAO
        PersonDAO personDAO = new PersonDAO(MyBatisConnectionFactory.getSqlSessionFactory());

        //create person bean to insert
        Person person = new Person();
        person.setName("Person 1");

        //( 1 ) insert person 
        personDAO.insert(person);

        //**set name of person
        person.setName("Person 2"); 
        //** insert another person
        int id = personDAO.insert(person);

        //( 2 ) select persons by id
        personDAO.selectById(id);

        //( 3 ) select all
        List<Person> persons = personDAO.selectAll();

        //**set name of all persons
        for(int i = 0; i < persons.size(); i++){
            persons.get(i).setName("Person Name "+i);
            //( 4 ) update person
            personDAO.update(persons.get(i));
        }

        //**check update
        persons = personDAO.selectAll();

    }
}

( 4 ) XML files

  • config.xml
  • Person.xml

config.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>
    <typeAliases>
        <typeAlias alias="Person" type="com.hmkcode.vo.Person"/>        
    </typeAliases>

    <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
            <!--  connecting to Local MySql -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/hmkcode"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
       </environment>
    </environments>
    <mappers>
       <mapper resource="com/hmkcode/mybatis/mapper/Person.xml"/>
    </mappers>
</configuration>

###Person.xml

( 5 ) Test Application

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值