spring jdbc访问mysql数据库

版权声明:未经本人同意,不得转发 https://blog.csdn.net/dgh112233/article/details/81239551

首先创建jdbc.properties配置文件

jdbc.url=jdbc\:mysql\://localhost:3306/one?useUnicode\=true&characterEncoding\=utf-8
jdbc.username=root
jdbc.password=123456
jdbc.driver=com.mysql.jdbc.Driver

其中url是指你的mysql数据库的地址,localhost是本地,3306是mysql数据库的接口,one是数据库名称(根据自己的数据库名称修改)。

创建数据库和表,数据库名称为one,表格名称为student。

将jdbc.properties注册到spring容器中,在applicationContext.xml中配置

<context:property-placeholder location="/jdbc.properties"/> //根据自己的路径修改

然后注册数据源,数据源就是你的数据库,使用的连接池是spring内置的连接池,也可以选择其他的连接池,但是就需要添加另外的jar,将红色部分修改即可,下面是最基本的设置,当然还有其他的可选属性。

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

创建Dao层:StudentDao接口和StudentDaoImpl类 。  dao层是用于访问和操作数据库的层。

public interface StudentDao {
    void insertStudent(Student t);
}

//说一下下面这个类,insertStudent()方法就是向数据库的student表插入一条记录,继承JdbcDaoSupport抽象类,才拥有了访问数据库的各种方法,比如删除,修改等,但是还要指明数据源是哪个数据库,现在还没有指明。

public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao {
    @Override
    public void insertStudent(Student t) {
        String sql="insert into student value(?,?,?)";
        this.getJdbcTemplate().update(sql,t.getName(),t.getAge(),t.getName());
    }
}

在applicationContext.xml里面配置StudentDaoImpl的bean,并且指明数据源

<bean id="dataDao" class="dao.impl.StudentDaoImpl">  //id随便写,但是最好和类的名字一致
    <property name="dataSource" ref="dataSource"></property>  //name随便写,最好一致
</bean>

最后写一个测试类来调用StudentDaoImpl类的方法来添加一条数据,Student类就是一个简单的类,

@Service   //由于使用了注解方式注入,那么applicationContext.xml里面就不用定义它的bean了。

public class Student{

    @Value("dgh")
    private String name;
    @Value("21")
    private String age;
    @Value("学生")
    private String job;
    public String getName() {return name; }
    public void setName(String name) {this.name = name;}
    public String getAge() {return age;}
    public void setAge(String age) {this.age = age;}
    public String getJob() {return job;}
    public void setJob(String job) {this.job = job;}

}

//下面是测试类

public class test{
    public StudentDaoImpl studentDaoImpl;

    public void setStudentDaoImpl(StudentDaoImpl threeDaoImpl) {
        this.studentDaoImpl = threeDaoImpl;
    }
    public void add(Student t) {
        studentDaoImpl.insertStudent(t);
    }
}

也需要在配置test类

<bean id="dataService" class="service.impl.StudentServiceImpl">
<property name="studentDaoImpl" ref="dataDao"></property>
</bean>

最后在main方法中:

ApplicationContext ac=new ClassPathXmlApplicationContext("test1/applicationContext.xml");
StudentServiceImpl a=(StudentServiceImpl)ac.getBean("dataService");
Student t=(Student)ac.getBean("student") ;
a.add(t);

猜你喜欢

转载自blog.csdn.net/dgh112233/article/details/81239551