mysql开发环境搭建_Java+MyBatis+MySQL开发环境搭建流程详解

主要搭建过程

1. pom.xml文件中加入mybatis和数据库依赖,这里使用mysql:

3.2.3

5.1.26

1.7.5

6.8.7

org.mybatis

mybatis

${mybatis.version}

mysql

mysql-connector-java

${mysql.version}

org.slf4j

slf4j-log4j12

${slf4j.api.version}

org.testng

testng

${testng.version}

2. 在类路径下创建mybatis的配置文件Configuration.xml

3. 执行创建数据库和表的sql:

-- Create the database named 'hbatis'.

-- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible.

CREATE DATABASE IF NOT EXISTS `hbatis`

DEFAULT CHARACTER SET = `UTF8`;

-- Create a table named 'User'

CREATE TABLE `user` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(50) DEFAULT NULL,

`age` int(11) DEFAULT NULL,

`address` varchar(200) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- Insert a test record

Insert INTO `user` VALUES ('1', 'john', '120', 'hangzhou,westlake');

4. com.john.hbatis.model.User类:

public class User {

private int id;

private String name;

private String age;

private String address;

// Getters and setters are omitted

// 如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.()

// 这时需要明确写出:

public User() {

}

public User(int id, String address) {

this.id = id;

this.address = address;

}

public User(String name, int age, String address) {

this.name = name;

this.age = age;

this.address = address;

}

}

com/john/hbatis/model路径下的User.xml

select * from `user` where id = #{id}

5. 测试类:

public class MyBatisBasicTest {

private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class);

private static SqlSessionFactory sqlSessionFactory;

private static Reader reader;

@BeforeClass

public static void initial() {

try {

reader = Resources.getResourceAsReader("Configuration.xml");

sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

} catch (IOException e) {

log.error("Error thrown while reading the configuration: {}", e);

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

log.error("Error thrown while closing the reader: {}", e);

}

}

}

}

@Test

public void queryTest() {

SqlSession session = sqlSessionFactory.openSession();

User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);

log.info("{}: {}", user.getName(), user.getAddress());

}

}

以接口方式交互数据上面的环境搭建是采用SqlSession的通用方法并强制转换的方式,存在着转换安全的问题:

User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);

可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现:

1. 新建接口类:

package com.john.hbatis.mapper;

import com.john.hbatis.model.User;

public interface IUserMapper {

User getUserById(int id);

}

2. 修改User.xml文件,确保namespace属性值和接口的全限定名相同,且id属性值和接口方法名相同:

3. 在MyBatisBasicTest类中添加测试方法:

@Test

public void queryInInterfaceWayTest() {

SqlSession session = sqlSessionFactory.openSession();

IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry异常。

User user = mapper.getUserById(1);

log.info("{}: {}", user.getName(), user.getAddress());

}

附:上面的实现是把sql语句放在XML文件中,并通过一定的约束来保证接口能够在XML中找到对应的SQL语句;

还有一种方式是通过接口+注解SQL方式来交互数据:

1. 新建接口类:

package com.john.hbatis.mapper;

import org.apache.ibatis.annotations.Select;

import com.john.hbatis.model.User;

public interface IUserMapper2 {

@Select({ "select * from `user` where id = #{id}" })

User getUserById(int id);

}

2. 在Configuration.xml文件中加入:

或在初始化语句中加入:

sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);

3. 相应修改上面的测试方法:

IUserMapper2 mapper = session.getMapper(IUserMapper2.class);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值