springdata筆記

applicationContext.xmljava

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd

       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd

       http://www.springframework.org/schema/data/jpa
       http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>

    <!--
    數據源 數據庫鏈接池

    建立 entityManagerFactory這件事 叫spring去作

    事務

    spring-data-jpa 相關配置

-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">


        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///springdata"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>

    </bean>
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--告訴框架  實體類所在包-->
        <property name="packagesToScan" value="com.itcast.pojo"></property>
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                
                <!--
            Vendor 產商 提供者 實現者的意思 Adapter 適配器
        -->

                <property name="database" value="MYSQL"/>
                <!--<property name="databasePlatform" value=""/>-->
                <!--<property name="generateDdl" value=""/>
                <property name="showSql" value=""/>-->

            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.format_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto" >update</prop>
            </props>
        </property>
    </bean>

    <!--事務管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven></tx:annotation-driven>
    <bean id="xx" class="com.itcast.demo.MyBean"></bean>

    <!--dao-->
    <jpa:repositories
            base-package="com.itcast.dao"
            entity-manager-factory-ref="entityManagerFactory"
            transaction-manager-ref="transactionManager"
    ></jpa:repositories>
</beans>

dao接口mysql

package com.itcast.dao;

import com.itcast.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface UserDao extends JpaRepository<User,Integer>,JpaSpecificationExecutor<User> {
}

實現spring

package com.itheima;

import static org.junit.Assert.assertTrue;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class AppTest {
    @Autowired
    private UserDao userDao;

    @Test
    @Transactional
    public void testSave() {
        User user = new User("小明", "111", 18);

        userDao.save(user);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testUpdate() {
        User user = new User("小明的爸爸", "111123", 28);
        user.setId(1);

        userDao.save(user);
    }
    @Test
    @Transactional
    public void testFindOne1() {
        //Optional 是jdk1.8 之後 額外增長的一個類

        //增長這個類目的是爲了防止空指針的
        //jdk設計人員想  強制你考慮空指針問題
        Optional<User> optional = userDao.findById(1);

        /*if (optional.isPresent()){
            User user = optional.get();
            //可是官方說 這麼用 落入下風  鼓勵這個


        }*/
        //鼓勵 orElse 傳入參數備選項
        User user = optional.orElse(new User());


        System.out.println(user);

    }
    //懶加載
    @Test
    @Transactional
    public void testFindOne2() {
        User user = userDao.getOne(1);
        System.out.println(user.getUsername());
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testRemove() {

        User user = userDao.findById(1).get();

        userDao.delete(user);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testFindByUsername() {

        User user = userDao.findByUsername("xiaohei");
        System.out.println(user);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testFindByUsernameAndPassword() {

        User user = userDao.findByUsernameAndPassword("xiaolv","11");
        System.out.println(user);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testFindByAgeAndPassword() {

        User user = userDao.findByAgeAndPassword(11,"123");
        System.out.println(user);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testDeleteByUsername() {
        userDao.deleteByUsername("xiaolv");
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testDeleteByUsername2() {
        userDao.deleteByUsername("xiaohu");
    }
}

 

 

 

 

註解:
@Entity//這是個實體類
@Id主鍵
@Column
@Transactional事物
@Rollback(false)回滾關閉sql

Bean工廠:數據庫


注入的
UserDao接口繼承JpaRepository<User,Integer>
JpaSpecificationExecutor<User>
在xml中配置了包掃描()
FactoryBean 建立工廠的bean
工廠建立好以後會直接調用afterPropertiesSet方法實現實例化~app

repository就是Dao!框架


ProxyFactory動態代理工廠
動態代理生成對象後走invokedom


UserDao中加入
@query("")語句
"from User where username=?1"spa

"from User where username=?1andpassword=?2"hibernate


"from User where username=:a"
java被編譯後 參數名會消失 因此:
@Param("a") 聲明佔位符 JVM不能改


"delete from User where username=?1"
@Modifying請支持刪除操做

原生"delete from user where username=? ,後面加聲明nativeQuery = true"


特殊的物種:
find By Username
以查詢爲例 以如下名命名規則的
find|read|query|get|stream+By+屬性名+[查詢方式]
_>規則在PartTree/class文件中

查詢方式:大於小於 模糊 等

刪除
remove|delete

判斷
Exist


計數
count

還有個沒看清 and all


規則:關鍵字+By+[查詢方式]+And|Or+屬性名+[查詢方式]......

.handeler .scanmerwww.jk1123.com/?p=124 老師的官網

相關文章
相關標籤/搜索