举例:学生(Student)和班级(ClassInfo)为例:
学生-----班级:为一对一的关系 即:一个学生只有一个相对应的班级。
嵌套结果使用双标签\<association>\</association>
一对一实体类创建如下:
1.数据库中创建班级表ClassInfo和学生表Student
create table classInfo(
cid int primary key auto_increment,
cname varchar(20),
cinfo varchar(20)
);
#插入测试数据
insert into classInfo(cname,cinfo) values ('一班','英语班');
insert into classInfo(cname,cinfo) values ('二班','数学班');
insert into classInfo(cname,cinfo) values ('三班','语文班');
#查询数据表
select * from classInfo;
#根据id查询数据
drop table if exists student;
#创建表
create table student(
sid int primary key auto_increment,
sname varchar(20),
sex varchar(2),
phone varchar(11),
address varchar(50),
cid int
);
#插入测试数据
insert into student(sname,sex,phone,address,cid) values ('张三','男',12345645,'河南',101);
insert into student(sname,sex,phone,address,cid) values ('李四','女',12345678,'海南',102);
insert into student(sname,sex,phone,address,cid) values ('王二','女',12345689,'云南',103);
insert into student(sname,sex,phone,address,cid) values ('小明','男',12345612,'湖南',102);
#查询数据表
select * from student;
#根据id查询数据
在idea中的bin包中导入jar包,配置mybatis.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> <properties resource="jdbc.properties" /> <settings> <setting name="logImpl" value="log4j"/> </settings> <typeAliases> <package name="com.su.bean"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <package name="com.su.dao"/> </mappers> </configuration>
3.在src中new一个file起名为jdbc(外部文件)和log4j(日志打印)
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/li jdbc.username=root jdbc.password=root
log4j.rootLogger=TRACE,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender #log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=wocao.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n log4j.logger.mapperNS =TRACE log4j.logger.com.mybatis=DEBUG log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.org.springframework=error log4j.logger.org.apache=ERROR log4j.logger.org.mybatis=DEBUG
4.1创建班级(ClassInfo)表的实体类